Programs & Examples On #Curves

"RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

1- first downlaod it(graphviz 2.38).

2- install org.graphviz.Graphviz-2.38-graphviz-2.38.

3- now add "C:\Program Files (x86)\Graphviz2.38\bin" and "C:\Program Files (x86)\Graphviz2.38\bin\dot.exe" to path like this video
note:in windows 8 you must use ; for path example: C:\Program Files;D:\Users;E:\file\

How to plot a function curve in R

I did some searching on the web, and this are some ways that I found:

The easiest way is using curve without predefined function

curve(x^2, from=1, to=50, , xlab="x", ylab="y")

enter image description here

You can also use curve when you have a predfined function

eq = function(x){x*x}
curve(eq, from=1, to=50, xlab="x", ylab="y")

enter image description here

If you want to use ggplot,

library("ggplot2")
eq = function(x){x*x}
ggplot(data.frame(x=c(1, 50)), aes(x=x)) + 
  stat_function(fun=eq)

enter image description here

Inline labels in Matplotlib

A simpler approach like the one Ioannis Filippidis do :

import matplotlib.pyplot as plt
import numpy as np

# evenly sampled time at 200ms intervals
tMin=-1 ;tMax=10
t = np.arange(tMin, tMax, 0.1)

# red dashes, blue points default
plt.plot(t, 22*t, 'r--', t, t**2, 'b')

factor=3/4 ;offset=20  # text position in view  
textPosition=[(tMax+tMin)*factor,22*(tMax+tMin)*factor]
plt.text(textPosition[0],textPosition[1]+offset,'22  t',color='red',fontsize=20)
textPosition=[(tMax+tMin)*factor,((tMax+tMin)*factor)**2+20]
plt.text(textPosition[0],textPosition[1]+offset, 't^2', bbox=dict(facecolor='blue', alpha=0.5),fontsize=20)
plt.show()

code python 3 on sageCell

How to make Java 6, which fails SSL connection with "SSL peer shut down incorrectly", succeed like Java 7?

update the server arguments from -Dhttps.protocols=SSLv3 to -Dhttps.protocols=TLSv1,SSLv3

Using Colormaps to set color of line in matplotlib

The error you are receiving is due to how you define jet. You are creating the base class Colormap with the name 'jet', but this is very different from getting the default definition of the 'jet' colormap. This base class should never be created directly, and only the subclasses should be instantiated.

What you've found with your example is a buggy behavior in Matplotlib. There should be a clearer error message generated when this code is run.

This is an updated version of your example:

import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
import numpy as np

# define some random data that emulates your indeded code:
NCURVES = 10
np.random.seed(101)
curves = [np.random.random(20) for i in range(NCURVES)]
values = range(NCURVES)

fig = plt.figure()
ax = fig.add_subplot(111)
# replace the next line 
#jet = colors.Colormap('jet')
# with
jet = cm = plt.get_cmap('jet') 
cNorm  = colors.Normalize(vmin=0, vmax=values[-1])
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
print scalarMap.get_clim()

lines = []
for idx in range(len(curves)):
    line = curves[idx]
    colorVal = scalarMap.to_rgba(values[idx])
    colorText = (
        'color: (%4.2f,%4.2f,%4.2f)'%(colorVal[0],colorVal[1],colorVal[2])
        )
    retLine, = ax.plot(line,
                       color=colorVal,
                       label=colorText)
    lines.append(retLine)
#added this to get the legend to work
handles,labels = ax.get_legend_handles_labels()
ax.legend(handles, labels, loc='upper right')
ax.grid()
plt.show()

Resulting in:

enter image description here

Using a ScalarMappable is an improvement over the approach presented in my related answer: creating over 20 unique legend colors using matplotlib

How I can get and use the header file <graphics.h> in my C++ program?

There is a modern port for this Turbo C graphics interface, it's called WinBGIM, which emulates BGI graphics under MinGW/GCC.

I haven't it tried but it looks promising. For example initgraph creates a window, and from this point you can draw into that window using the good old functions, at the end closegraph deletes the window. It also has some more advanced extensions (eg. mouse handling and double buffering).

When I first moved from DOS programming to Windows I didn't have internet, and I begged for something simple like this. But at the end I had to learn how to create windows and how to handle events and use device contexts from the offline help of the Windows SDK.

Overlaying histograms with ggplot2 in R

While only a few lines are required to plot multiple/overlapping histograms in ggplot2, the results are't always satisfactory. There needs to be proper use of borders and coloring to ensure the eye can differentiate between histograms.

The following functions balance border colors, opacities, and superimposed density plots to enable the viewer to differentiate among distributions.

Single histogram:

plot_histogram <- function(df, feature) {
    plt <- ggplot(df, aes(x=eval(parse(text=feature)))) +
    geom_histogram(aes(y = ..density..), alpha=0.7, fill="#33AADE", color="black") +
    geom_density(alpha=0.3, fill="red") +
    geom_vline(aes(xintercept=mean(eval(parse(text=feature)))), color="black", linetype="dashed", size=1) +
    labs(x=feature, y = "Density")
    print(plt)
}

Multiple histogram:

plot_multi_histogram <- function(df, feature, label_column) {
    plt <- ggplot(df, aes(x=eval(parse(text=feature)), fill=eval(parse(text=label_column)))) +
    geom_histogram(alpha=0.7, position="identity", aes(y = ..density..), color="black") +
    geom_density(alpha=0.7) +
    geom_vline(aes(xintercept=mean(eval(parse(text=feature)))), color="black", linetype="dashed", size=1) +
    labs(x=feature, y = "Density")
    plt + guides(fill=guide_legend(title=label_column))
}

Usage:

Simply pass your data frame into the above functions along with desired arguments:

plot_histogram(iris, 'Sepal.Width')

enter image description here

plot_multi_histogram(iris, 'Sepal.Width', 'Species')

enter image description here

The extra parameter in plot_multi_histogram is the name of the column containing the category labels.

We can see this more dramatically by creating a dataframe with many different distribution means:

a <-data.frame(n=rnorm(1000, mean = 1), category=rep('A', 1000))
b <-data.frame(n=rnorm(1000, mean = 2), category=rep('B', 1000))
c <-data.frame(n=rnorm(1000, mean = 3), category=rep('C', 1000))
d <-data.frame(n=rnorm(1000, mean = 4), category=rep('D', 1000))
e <-data.frame(n=rnorm(1000, mean = 5), category=rep('E', 1000))
f <-data.frame(n=rnorm(1000, mean = 6), category=rep('F', 1000))
many_distros <- do.call('rbind', list(a,b,c,d,e,f))

Passing data frame in as before (and widening chart using options):

options(repr.plot.width = 20, repr.plot.height = 8)
plot_multi_histogram(many_distros, 'n', 'category')

enter image description here

Plotting multiple curves same graph and same scale

points or lines comes handy if

  • y2 is generated later, or
  • the new data does not have the same x but still should go into the same coordinate system.

As your ys share the same x, you can also use matplot:

matplot (x, cbind (y1, y2), pch = 19)

matplot (x, cbind (y1, y2), pch = 19)

(without the pch matplopt will plot the column numbers of the y matrix instead of dots).

Access parent DataContext from DataTemplate

I had problems with the relative source in Silverlight. After searching and reading I did not find a suitable solution without using some additional Binding library. But, here is another approach for gaining access to the parent DataContext by directly referencing an element of which you know the data context. It uses Binding ElementName and works quite well, as long as you respect your own naming and don't have heavy reuse of templates/styles across components:

<ItemsControl x:Name="level1Lister" ItemsSource={Binding MyLevel1List}>
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <Button Content={Binding MyLevel2Property}
              Command={Binding ElementName=level1Lister,
                       Path=DataContext.MyLevel1Command}
              CommandParameter={Binding MyLevel2Property}>
      </Button>
    <DataTemplate>
  <ItemsControl.ItemTemplate>
</ItemsControl>

This also works if you put the button into Style/Template:

<Border.Resources>
  <Style x:Key="buttonStyle" TargetType="Button">
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="Button">
          <Button Command={Binding ElementName=level1Lister,
                                   Path=DataContext.MyLevel1Command}
                  CommandParameter={Binding MyLevel2Property}>
               <ContentPresenter/>
          </Button>
        </ControlTemplate>
      </Setter.Value>
    </Setter>
  </Style>
</Border.Resources>

<ItemsControl x:Name="level1Lister" ItemsSource={Binding MyLevel1List}>
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <Button Content="{Binding MyLevel2Property}" 
              Style="{StaticResource buttonStyle}"/>
    <DataTemplate>
  <ItemsControl.ItemTemplate>
</ItemsControl>

At first I thought that the x:Names of parent elements are not accessible from within a templated item, but since I found no better solution, I just tried, and it works fine.

Plotting 4 curves in a single plot, with 3 y-axes

I know of plotyy that allows you to have two y-axes, but no "plotyyy"!

Perhaps you can normalize the y values to have the same scale (min/max normalization, zscore standardization, etc..), then you can just easily plot them using normal plot, hold sequence.

Here's an example:

%# random data
x=1:20;
y = [randn(20,1)*1 + 0 , randn(20,1)*5 + 10 , randn(20,1)*0.3 + 50];

%# plotyy
plotyy(x,y(:,1), x,y(:,3))

%# orginial
figure
subplot(221), plot(x,y(:,1), x,y(:,2), x,y(:,3))
title('original'), legend({'y1' 'y2' 'y3'})

%# normalize: (y-min)/(max-min) ==> [0,1]
yy = bsxfun(@times, bsxfun(@minus,y,min(y)), 1./range(y));
subplot(222), plot(x,yy(:,1), x,yy(:,2), x,yy(:,3))
title('minmax')

%# standarize: (y - mean) / std ==> N(0,1)
yy = zscore(y);
subplot(223), plot(x,yy(:,1), x,yy(:,2), x,yy(:,3))
title('zscore')

%# softmax normalization with logistic sigmoid ==> [0,1]
yy = 1 ./ ( 1 + exp( -zscore(y) ) );
subplot(224), plot(x,yy(:,1), x,yy(:,2), x,yy(:,3))
title('softmax')

plotyy normalization

How to convert a 3D point into 2D perspective projection?

I'm not sure at what level you're asking this question. It sounds as if you've found the formulas online, and are just trying to understand what it does. On that reading of your question I offer:

  • Imagine a ray from the viewer (at point V) directly towards the center of the projection plane (call it C).
  • Imagine a second ray from the viewer to a point in the image (P) which also intersects the projection plane at some point (Q)
  • The viewer and the two points of intersection on the view plane form a triangle (VCQ); the sides are the two rays and the line between the points in the plane.
  • The formulas are using this triangle to find the coordinates of Q, which is where the projected pixel will go

What is the difference between LATERAL and a subquery in PostgreSQL?

First, Lateral and Cross Apply is same thing. Therefore you may also read about Cross Apply. Since it was implemented in SQL Server for ages, you will find more information about it then Lateral.

Second, according to my understanding, there is nothing you can not do using subquery instead of using lateral. But:

Consider following query.

Select A.*
, (Select B.Column1 from B where B.Fk1 = A.PK and Limit 1)
, (Select B.Column2 from B where B.Fk1 = A.PK and Limit 1)
FROM A 

You can use lateral in this condition.

Select A.*
, x.Column1
, x.Column2
FROM A LEFT JOIN LATERAL (
  Select B.Column1,B.Column2,B.Fk1 from B  Limit 1
) x ON X.Fk1 = A.PK

In this query you can not use normal join, due to limit clause. Lateral or Cross Apply can be used when there is not simple join condition.

There are more usages for lateral or cross apply but this is most common one I found.

Continuous Integration vs. Continuous Delivery vs. Continuous Deployment

Difference between Continuous Integration, Continuous delivery and continuous deployment

enter image description here

Xcode error: Code signing is required for product type 'Application' in SDK 'iOS 10.0'

In case you are still having this problem, click on the Tests and select a team for them too.

Undo a git stash

You can just run:

git stash pop

and it will unstash your changes.

If you want to preserve the state of files (staged vs. working), use

git stash apply --index

Suppress console output in PowerShell

It is a duplicate of this question, with an answer that contains a time measurement of the different methods.

Conclusion: Use [void] or > $null.

Why would $_FILES be empty when uploading files to PHP?

I too had problems with $_FILES empty. The above check-list do not mention MultiViews in .htaccess, httpd.conf or httpd-vhost.conf.

If you have MultiViews set in the options directive for your directory containing the web site, $_FILES will be empty, even though Content-Length header if showing that the file i uploaded.

How to check if curl is enabled or disabled

Its always better to go for a generic reusable function in your project which returns whether the extension loaded. You can use the following function to check -

function isExtensionLoaded($extension_name){
    return extension_loaded($extension_name);
}

Usage

echo isExtensionLoaded('curl');
echo isExtensionLoaded('gd');

"getaddrinfo failed", what does that mean?

It most likely means the hostname can't be resolved.

import socket
socket.getaddrinfo('localhost', 8080)

If it doesn't work there, it's not going to work in the Bottle example. You can try '127.0.0.1' instead of 'localhost' in case that's the problem.

Local package.json exists, but node_modules missing

npm start runs a script that the app maker built for easy starting of the app npm install installs all the packages in package.json

run npm install first

then run npm start

Why can't Python parse this JSON data?

If you're using Python3, you can try changing your (connection.json file) JSON to:

{
  "connection1": {
    "DSN": "con1",
    "UID": "abc",
    "PWD": "1234",
    "connection_string_python":"test1"
  }
  ,
  "connection2": {
    "DSN": "con2",
    "UID": "def",
    "PWD": "1234"
  }
}

Then using the following code:

connection_file = open('connection.json', 'r')
conn_string = json.load(connection_file)
conn_string['connection1']['connection_string_python'])
connection_file.close()
>>> test1

Failed to resolve: com.android.support:cardview-v7:26.0.0 android

For me I just had to clean my project.

Build -> Clean Project

Another time I had to:

File -> Sync Project with Gradle Files.

How do you count the lines of code in a Visual Studio solution?

I came up with a quick and dirty powershell script for counting lines in a folder structure. It's not nearly as full featured as some of the other tools referenced in other answers, but I think it's good enough to provide a rough comparison of the size of code files relative to one another in a project or solution.

The script can be found here:

https://gist.github.com/1674457

How to debug Javascript with IE 8

You can get more information about IE8 Developer Toolbar debugging at Debugging JScript or Debugging Script with the Developer Tools.

How to display Base64 images in HTML?

You need to specify correct Content-type, Content-encoding and charset like

 data:image/jpeg;charset=utf-8;base64, 

according to the syntax of the data URI scheme:

 data:[<media type>][;charset=<character set>][;base64],<data>

get client time zone from browser

For now, the best bet is probably jstz as suggested in mbayloon's answer.

For completeness, it should be mentioned that there is a standard on it's way: Intl. You can see this in Chrome already:

> Intl.DateTimeFormat().resolvedOptions().timeZone
"America/Los_Angeles"

(This doesn't actually follow the standard, which is one more reason to stick with the library)

JPA COUNT with composite primary key query not working

Use count(d.ertek) or count(d.id) instead of count(d). This can be happen when you have composite primary key at your entity.

How to set height property for SPAN

Why do you need a span in this case? If you want to style the height could you just use a div? You might try a div with display: inline, although that might have the same issue since you'd in effect be doing the same thing as a span.

JavaScript: Is there a way to get Chrome to break on all errors?

Unfortunately, it the Developer Tools in Chrome seem to be unable to "stop on all errors", as Firebug does.

MySQL Query to select data from last week?

You can make your calculation in php and then add it to your query:

$date = date('Y-m-d H:i:s',time()-(7*86400)); // 7 days ago

$sql = "SELECT * FROM table WHERE date <='$date' ";

now this will give the date for a week ago

How to put two divs side by side

This is just a simple(not-responsive) HTML/CSS translation of the wireframe you provided.

enter image description here

HTML

<div class="container">

  <header>
    <div class="logo">Logo</div>
    <div class="menu">Email/Password</div>
  </header>

  <div class="first-box">
    <p>Video Explaning Site</p>
  </div>

  <div class="second-box">
    <p>Sign up Info</p>
  </div>

  <footer>
    <div>Website Info</div>
  </footer>

</div>

CSS

.container {
  width:900px; 
  height: 150px;
}

header {
  width:900px; 
  float:left; 
  background: pink; 
  height: 50px;
}

.logo {
  float: left;
  padding: 15px
}

.menu {
  float: right;
  padding: 15px
}

.first-box {
  width:300px; 
  float:left; 
  background: green; 
  height: 150px;
  margin: 50px
}

.first-box p {
  color: #ffffff;
  padding-left: 80px;
  padding-top: 50px;
}

.second-box {
  width:300px; 
  height: 150px; 
  float:right; 
  background: blue;
  margin: 50px
}

.second-box p {
  color: #ffffff;
  padding-left: 110px;
  padding-top: 50px;
}

footer {
  width:900px; 
  float:left; 
  background: black; 
  height: 50px;
  color: #ffffff;
}

footer div {
  padding: 15px;
}

Select rows where column is null

for some reasons IS NULL may not work with some column data type i was in need to get all the employees that their English full name is missing ,I've used :

**SELECT emp_id ,Full_Name_Ar,Full_Name_En from employees where Full_Name_En = ' ' or Full_Name_En is null **

How to receive POST data in django

res = request.GET['paymentid'] will raise a KeyError if paymentid is not in the GET data.

Your sample php code checks to see if paymentid is in the POST data, and sets $payID to '' otherwise:

$payID = isset($_POST['paymentid']) ? $_POST['paymentid'] : ''

The equivalent in python is to use the get() method with a default argument:

payment_id = request.POST.get('payment_id', '')

while debugging, this is what I see in the response.GET: <QueryDict: {}>, request.POST: <QueryDict: {}>

It looks as if the problem is not accessing the POST data, but that there is no POST data. How are you are debugging? Are you using your browser, or is it the payment gateway accessing your page? It would be helpful if you shared your view.

Once you are managing to submit some post data to your page, it shouldn't be too tricky to convert the sample php to python.

Remove last commit from remote git repository

Be careful that this will create an "alternate reality" for people who have already fetch/pulled/cloned from the remote repository. But in fact, it's quite simple:

git reset HEAD^ # remove commit locally
git push origin +HEAD # force-push the new HEAD commit

If you want to still have it in your local repository and only remove it from the remote, then you can use:

git push origin +HEAD^:<name of your branch, most likely 'master'>

Multiple Image Upload PHP form with one input

$total = count($_FILES['txt_gallery']['name']);
            $filename_arr = [];
            $filename_arr1 = [];
            for( $i=0 ; $i < $total ; $i++ ) {
              $tmpFilePath = $_FILES['txt_gallery']['tmp_name'][$i];
              if ($tmpFilePath != ""){
                $newFilePath = "../uploaded/" .date('Ymdhis').$i.$_FILES['txt_gallery']['name'][$i];
                $newFilePath1 = date('Ymdhis').$i.$_FILES['txt_gallery']['name'][$i];
                if(move_uploaded_file($tmpFilePath, $newFilePath)) {
                  $filename_arr[] = $newFilePath;
                  $filename_arr1[] = $newFilePath1;

                }
              }
            }
            $file_names = implode(',', $filename_arr1);
            var_dump($file_names); exit;

Variables not showing while debugging in Eclipse

Also: your process needs to be suspended for Eclipse to show variables. If it is running, Eclipse won't show any variable.

To suspend a thread, select a thread in the "debug" view, and hit "Suspend"

How to send UTF-8 email?

I'm using rather specified charset (ISO-8859-2) because not every mail system (for example: http://10minutemail.com) can read UTF-8 mails. If you need this:

function utf8_to_latin2($str)
{
    return iconv ( 'utf-8', 'ISO-8859-2' , $str );
}
function my_mail($to,$s,$text,$form, $reply)
    {
        mail($to,utf8_to_latin2($s),utf8_to_latin2($text),
        "From: $form\r\n".
        "Reply-To: $reply\r\n".
        "X-Mailer: PHP/" . phpversion());
    }

I have made another mailer function, because apple device could not read well the previous version.

function utf8mail($to,$s,$body,$from_name="x",$from_a = "[email protected]", $reply="[email protected]")
{
    $s= "=?utf-8?b?".base64_encode($s)."?=";
    $headers = "MIME-Version: 1.0\r\n";
    $headers.= "From: =?utf-8?b?".base64_encode($from_name)."?= <".$from_a.">\r\n";
    $headers.= "Content-Type: text/plain;charset=utf-8\r\n";
    $headers.= "Reply-To: $reply\r\n";  
    $headers.= "X-Mailer: PHP/" . phpversion();
    mail($to, $s, $body, $headers);
}

How to set aliases in the Git Bash for Windows?

There is two easy way to set the alias.

  1. Using Bash
  2. Updating .gitconfig file

Using Bash

Open bash terminal and type git command. For instance:

$ git config --global alias.a add
$ git config --global alias.aa 'add .'
$ git config --global alias.cm 'commit -m'
$ git config --global alias.s status
---
---

It will eventually add those aliases on .gitconfig file.

Updating .gitconfig file

Open .gitconfig file located at 'C:\Users\username\.gitconfig' in Windows environment. Then add following lines:

[alias]  
a = add  
aa = add . 
cm = commit -m 
gau = add --update 
au = add --update
b = branch
---
---

How to kill an application with all its activities?

When the user wishes to exit all open activities, they should press a button which loads the first Activity that runs when your app starts, in my case "LoginActivity".

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);

The above code clears all the activities except for LoginActivity. LoginActivity is the first activity that is brought up when the user runs the program. Then put this code inside the LoginActivity's onCreate, to signal when it should self destruct when the 'Exit' message is passed.

    if (getIntent().getBooleanExtra("EXIT", false)) {
         finish();
    }

The answer you get to this question from the Android platform is: "Don't make an exit button. Finish activities the user no longer wants, and the Activity manager will clean them up as it sees fit."

Numpy: Get random set of rows from 2D array

Another option is to create a random mask if you just want to down-sample your data by a certain factor. Say I want to down-sample to 25% of my original data set, which is currently held in the array data_arr:

# generate random boolean mask the length of data
# use p 0.75 for False and 0.25 for True
mask = numpy.random.choice([False, True], len(data_arr), p=[0.75, 0.25])

Now you can call data_arr[mask] and return ~25% of the rows, randomly sampled.

Looping through a hash, or using an array in PowerShell

A short traverse could be given too using the sub-expression operator $( ), which returns the result of one or more statements.

$hash = @{ a = 1; b = 2; c = 3}

forEach($y in $hash.Keys){
    Write-Host "$y -> $($hash[$y])"
}

Result:

a -> 1
b -> 2
c -> 3

PHP: Inserting Values from the Form into MySQL

There are two problems in your code.

  1. No action found in form.
  2. You have not executed the query mysqli_query()

dbConfig.php

<?php

$conn=mysqli_connect("localhost","root","password","testDB");

if(!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}

?>

index.php

 include('dbConfig.php');

<!Doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="$1">
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" type="text/css" href="style.css">

<title>test</title>


</head>
<body>

 <?php

  if(isset($_POST['save']))
{
    $sql = "INSERT INTO users (username, password, email)
    VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')";

    $result = mysqli_query($conn,$sql);
}

?>

<form action="index.php" method="post"> 
<label id="first"> First name:</label><br/>
<input type="text" name="username"><br/>

<label id="first">Password</label><br/>
<input type="password" name="password"><br/>

<label id="first">Email</label><br/>
<input type="text" name="email"><br/>

<button type="submit" name="save">save</button>

</form>

</body>
</html>

Linux command line howto accept pairing for bluetooth device without pin

This worked like a charm for me, of-course it requires super-user privileges :-)

# hcitool cc <target-bdaddr>; hcitool auth <target-bdaddr>

To get <target-bdaddr> you may issue below command:
$ hcitool scan

Note: Exclude # & $ as they are command line prompts.

Courtesy

html 5 audio tag width

You can use html and be a boss with simple things :

<embed src="music.mp3" width="3000" height="200" controls>

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

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

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

According to this test, results are :

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

Conclusion

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

Set Page Title using PHP

It'll be tricky to rearrange your code to make this work, but I'll try :)

So, put this at the top of your code:

<?php require_once('mysql.php'); ?>

The top of the file should look like:

<?php require_once('mysql.php'); ?>
<html>
    <head>

    <meta name="keywords" content="Mac user Ultan Casey TheCompuGeeks UltanKC">
    <title>Ultan.me - <?php echo htmlspecialchars($title); ?> </title>

Then, create a file called mysql.php in the same directory that the file which contains the code you quoted is in.

Put this is mysql.php:

<?php
mysql_connect ('localhost', 'root', 'root');
mysql_select_db ('ultankc');

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    die("Invalid ID specified.");
}

$id = (int)$_GET['id'];
$sql = "SELECT * FROM php_blog WHERE id='$id' LIMIT 1";

$result = mysql_query($sql) or print ("Can't select entry from table php_blog.<br />" .       $sql . "<br />" . mysql_error());

$res = mysql_fetch_assoc($result); 

$date = date("l F d Y", $res['timestamp']);
$title = $res['title'];
$entry = $res['entry'];
$get_categories = mysql_query("SELECT * FROM php_blog_categories WHERE `category_id` = $res['category']");
$category = mysql_fetch_array($get_categories);

?>

Well, hope that helped :)

How to check a string against null in java?

Simple method:

public static boolean isBlank(String value) {
    return (value == null || value.equals("") || value.equals("null") || value.trim().equals(""));
}

How to access List elements

Learn python the hard way ex 34

try this

animals = ['bear' , 'python' , 'peacock', 'kangaroo' , 'whale' , 'platypus']

# print "The first (1st) animal is at 0 and is a bear." 

for i in range(len(animals)):
    print "The %d animal is at %d and is a %s" % (i+1 ,i, animals[i])

# "The animal at 0 is the 1st animal and is a bear."

for i in range(len(animals)):
    print "The animal at %d is the %d and is a %s " % (i, i+1, animals[i])

How to debug heap corruption errors?

One quick tip, that I got from Detecting access to freed memory is this:

If you want to locate the error quickly, without checking every statement that accesses the memory block, you can set the memory pointer to an invalid value after freeing the block:

#ifdef _DEBUG // detect the access to freed memory
#undef free
#define free(p) _free_dbg(p, _NORMAL_BLOCK); *(int*)&p = 0x666;
#endif

Property [title] does not exist on this collection instance

A person might get this while working with factory functions, so I can confirm this is valid syntax:

$user = factory(User::class, 1)->create()->first();

You might see the collection instance error if you do something like:

$user = factory(User::class, 1)->create()->id;

so change it to:

$user = factory(User::class, 1)->create()->first()->id;

Align Div at bottom on main Div

Please try this:

#b {
display: -webkit-inline-flex;
display: -moz-inline-flex;
display: inline-flex;

-webkit-flex-flow: row nowrap;
-moz-flex-flow: row nowrap;
flex-flow: row nowrap;

-webkit-align-items: flex-end;
-moz-align-items: flex-end;
align-items: flex-end;}

Here's a JSFiddle demo: http://jsfiddle.net/rudiedirkx/7FGKN/.

What are the differences between normal and slim package of jquery?

I found a difference when creating a Form Contact: slim (recommended by boostrap 4.5):

  • After sending an email the global variables get stuck, and that makes if the user gives f5 (reload page) it is sent again. min:
  • The previous error will be solved. how i suffered!

Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

As mentioned above the following would solve the problem: mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

However in my case the provider did this [0..1] or [0..*] serialization rather as a bug and I could not enforce fixing. On the other hand it did not want to impact my strict mapper for all other cases which needs to be validated strictly.

So I did a Jackson NASTY HACK (which should not be copied in general ;-) ), especially because my SingleOrListElement had only few properties to patch:

@JsonProperty(value = "SingleOrListElement", access = JsonProperty.Access.WRITE_ONLY)
private Object singleOrListElement; 

public List<SingleOrListElement> patch(Object singleOrListElement) {
  if (singleOrListElement instanceof List) {
    return (ArrayList<SingleOrListElement>) singleOrListElement;
  } else {
    LinkedHashMap map = (LinkedHashMap) singleOrListElement;
    return Collections.singletonList(SingletonList.builder()
                            .property1((String) map.get("p1"))
                            .property2((Integer) map.get("p2"))
                            .build());
  }

Why is it faster to check if dictionary contains the key, rather than catch the exception in case it doesn't?

On the one hand, throwing exceptions is inherently expensive, because the stack has to be unwound etc.
On the other hand, accessing a value in a dictionary by its key is cheap, because it's a fast, O(1) operation.

BTW: The correct way to do this is to use TryGetValue

obj item;
if(!dict.TryGetValue(name, out item))
    return null;
return item;

This accesses the dictionary only once instead of twice.
If you really want to just return null if the key doesn't exist, the above code can be simplified further:

obj item;
dict.TryGetValue(name, out item);
return item;

This works, because TryGetValue sets item to null if no key with name exists.

submitting a form when a checkbox is checked

Use JavaScript by adding an onChange attribute to your input tags

<input onChange="this.form.submit()" ... />

Writing/outputting HTML strings unescaped

Complete example for using template functions in RazorEngine (for email generation, for example):

@model SomeModel
@{
    Func<PropertyChangeInfo, object> PropInfo =
        @<tr class="property">
            <td>
                @item.PropertyName                
            </td>
            <td class="value">
                <small class="old">@item.OldValue</small>
                <small class="new">@item.CurrentValue</small>                
            </td>
        </tr>;
}

<body>

@{ WriteLiteral(PropInfo(new PropertyChangeInfo("p1", @Model.Id, 2)).ToString()); }

</body>

Dilemma: when to use Fragments vs Activities:

Since Jetpack, Single-Activity app is the preferred architecture. Usefull especially with the Navigation Architecture Component.

source

"Port 4200 is already in use" when running the ng serve command

ng serve --port 122345 is worked fine for me.

How to run functions in parallel?

In 2021 the easiest way is to use asyncio:

import asyncio, time

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():

    task1 = asyncio.create_task(
        say_after(4, 'hello'))

    task2 = asyncio.create_task(
        say_after(3, 'world'))

    print(f"started at {time.strftime('%X')}")

    # Wait until both tasks are completed (should take
    # around 2 seconds.)
    await task1
    await task2

    print(f"finished at {time.strftime('%X')}")


asyncio.run(main())

References:

[1] https://docs.python.org/3/library/asyncio-task.html

How to write specific CSS for mozilla, chrome and IE

Since you also have PHP in the tag, I'm going to suggest some server side options.

The easiest solution is the one most people suggest here. The problem I generally have with this, is that it can causes your CSS files or <style> tags to be up to 20 times bigger than your html documents and can cause browser slowdowns for parsing and processing tags that it can't understand -moz-border-radius vs -webkit-border-radius

The second best solution(i've found) is to have php output your actual css file i.e.

<link rel="stylesheet" type="text/css" href="mycss.php">

where

<?php
header("Content-Type: text/css");
if( preg_match("/chrome/", $_SERVER['HTTP_USER_AGENT']) ) {
  // output chrome specific css style
} else {
  // output default css style
}
?>

This allows you to create smaller easier to process files for the browser.

The best method I've found, is specific to Apache though. The method is to use mod_rewrite or mod_perl's PerlMapToStorageHandler to remap the URL to a file on the system based on the rendering engine.

say your website is http://www.myexample.com/ and it points to /srv/www/html. For chrome, if you ask for main.css, instead of loading /srv/www/html/main.css it checks to see if there is a /srv/www/html/main.webkit.css and if it exists, it dump that, else it'll output the main.css. For IE, it tries main.trident.css, for firefox it tries main.gecko.css. Like above, it allows me to create smaller, more targeted, css files, but it also allows me to use caching better, as the browser will attempt to redownload the file, and the web server will present the browser with proper 304's to tell it, you don't need to redownload it. It also allows my web developers a bit more freedom without for them having to write backend code to target platforms. I also have .js files being redirected to javascript engines as well, for main.js, in chrome it tries main.v8.js, in safari, main.nitro.js, in firefox, main.gecko.js. This allows for outputting of specific javascript that will be faster(less browser testing code/feature testing). Granted the developers don't have to target specific and can write a main.js and not make main.<js engine>.js and it'll load that normally. i.e. having a main.js and a main.jscript.js file means that IE gets the jscript one, and everyone else gets the default js, same with the css files.

Rails 3 execute custom sql query without a model

Maybe try this:

ActiveRecord::Base.establish_connection(...)
ActiveRecord::Base.connection.execute(...)

Perform commands over ssh with Python

Keep it simple. No libraries required.

import subprocess

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

Split a large dataframe into a list of data frames based on common value in column

Stumbled across this answer and I actually wanted BOTH groups (data containing that one user and data containing everything but that one user). Not necessary for the specifics of this post, but I thought I would add in case someone was googling the same issue as me.

df <- data.frame(
     ran_data1=rnorm(125),
     ran_data2=rnorm(125),
     g=rep(factor(LETTERS[1:5]), 25)
 )

test_x = split(df,df$g)[['A']]
test_y = split(df,df$g!='A')[['TRUE']]

Here's what it looks like:

head(test_x)
            x          y g
1   1.1362198  1.2969541 A
6   0.5510307 -0.2512449 A
11  0.0321679  0.2358821 A
16  0.4734277 -1.2889081 A
21 -1.2686151  0.2524744 A

> head(test_y)
            x          y g
2 -2.23477293  1.1514810 B
3 -0.46958938 -1.7434205 C
4  0.07365603  0.1111419 D
5 -1.08758355  0.4727281 E
7  0.28448637 -1.5124336 B
8  1.24117504  0.4928257 C

how to add a day to a date using jquery datepicker

Try this:

 $('.pickupDate').change(function() {
  var date2 = $('.pickupDate').datepicker('getDate', '+1d'); 
  date2.setDate(date2.getDate()+1); 
  $('.dropoffDate').datepicker('setDate', date2);
});

How do I cancel form submission in submit button onclick event?

You need to change

onclick='btnClick();'

to

onclick='return btnClick();'

and

cancelFormSubmission();

to

return false;

That said, I'd try to avoid the intrinsic event attributes in favour of unobtrusive JS with a library (such as YUI or jQuery) that has a good event handling API and tie into the event that really matters (i.e. the form's submit event instead of the button's click event).

Binding List<T> to DataGridView in WinForm

List does not implement IBindingList so the grid does not know about your new items.

Bind your DataGridView to a BindingList<T> instead.

var list = new BindingList<Person>(persons);
myGrid.DataSource = list;

But I would even go further and bind your grid to a BindingSource

var list = new List<Person>()
{
    new Person { Name = "Joe", },
    new Person { Name = "Misha", },
};
var bindingList = new BindingList<Person>(list);
var source = new BindingSource(bindingList, null);
grid.DataSource = source;

How to change the time format (12/24 hours) of an <input>?

Support of this type is still very poor. Opera shows it in a way you want. Chrome 23 shows it with seconds and AM/PM, in 24 version (dev branch at this moment) it will rid of seconds (if possible), but no information about AM/PM.
It's not want you possibly want, but at this point the only option I see to achieve your time picker format is usage of javascript.

VS Code - Search for text in all files in a directory

You can do Edit, Find in Files (or Ctrl+Shift+F - default key binding, Cmd+Shift+F on MacOS) to search the Currently open Folder.

There is an ellipsis on the dialog where you can include/exclude files, and options in the search box for matching case/word and using Regex.

Detect iPad users using jQuery?

Although the accepted solution is correct for iPhones, it will incorrectly declare both isiPhone and isiPad to be true for users visiting your site on their iPad from the Facebook app.

The conventional wisdom is that iOS devices have a user agent for Safari and a user agent for the UIWebView. This assumption is incorrect as iOS apps can and do customize their user agent. The main offender here is Facebook.

Compare these user agent strings from iOS devices:

# iOS Safari
iPad: Mozilla/5.0 (iPad; CPU OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B176 Safari/7534.48.3
iPhone: Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3

# UIWebView
iPad: Mozilla/5.0 (iPad; CPU OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Mobile/98176
iPhone: Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Mobile/8B117

# Facebook UIWebView
iPad: Mozilla/5.0 (iPad; U; CPU iPhone OS 5_1_1 like Mac OS X; en_US) AppleWebKit (KHTML, like Gecko) Mobile [FBAN/FBForIPhone;FBAV/4.1.1;FBBV/4110.0;FBDV/iPad2,1;FBMD/iPad;FBSN/iPhone OS;FBSV/5.1.1;FBSS/1; FBCR/;FBID/tablet;FBLC/en_US;FBSF/1.0]
iPhone: Mozilla/5.0 (iPhone; U; CPU iPhone OS 5_1_1 like Mac OS X; ru_RU) AppleWebKit (KHTML, like Gecko) Mobile [FBAN/FBForIPhone;FBAV/4.1;FBBV/4100.0;FBDV/iPhone3,1;FBMD/iPhone;FBSN/iPhone OS;FBSV/5.1.1;FBSS/2; tablet;FBLC/en_US]

Note that on the iPad, the Facebook UIWebView's user agent string includes 'iPhone'.

The old way to identify iPhone / iPad in JavaScript:

IS_IPAD = navigator.userAgent.match(/iPad/i) != null;
IS_IPHONE = navigator.userAgent.match(/iPhone/i) != null) || (navigator.userAgent.match(/iPod/i) != null);

If you were to go with this approach for detecting iPhone and iPad, you would end up with IS_IPHONE and IS_IPAD both being true if a user comes from Facebook on an iPad. That could create some odd behavior!

The correct way to identify iPhone / iPad in JavaScript:

IS_IPAD = navigator.userAgent.match(/iPad/i) != null;
IS_IPHONE = (navigator.userAgent.match(/iPhone/i) != null) || (navigator.userAgent.match(/iPod/i) != null);
if (IS_IPAD) {
  IS_IPHONE = false;
}

We declare IS_IPHONE to be false on iPads to cover for the bizarre Facebook UIWebView iPad user agent. This is one example of how user agent sniffing is unreliable. The more iOS apps that customize their user agent, the more issues user agent sniffing will have. If you can avoid user agent sniffing (hint: CSS Media Queries), DO IT.

How to remove "Server name" items from history of SQL Server Management Studio

File SqlStudio.bin actually contains binary serialized data of type "Microsoft.SqlServer.Management.UserSettings.SqlStudio".

Using BinaryFormatter class you can write simple .NET application in order to edit file content.

JavaScript CSS how to add and remove multiple CSS classes to an element

Try this:

function addClass(element, value) {
  if(!element.className) {
    element.className = value;
  } else {
    newClassName = element.className;
    newClassName+= " ";
    newClassName+= value;
    element.className = newClassName;
  }
}

Similar logic could be used to make a removeClass function.

read string from .resx file in C#

The easiest way to do this is:

  1. Create an App_GlobalResources system folder and add a resource file to it e.g. Messages.resx
  2. Create your entries in the resource file e.g. ErrorMsg = This is an error.
  3. Then to access that entry: string errormsg = Resources.Messages.ErrorMsg

How to extract numbers from string in c?

A possible solution using sscanf() and scan sets:

const char* s = "ab234cid*(s349*(20kd";
int i1, i2, i3;
if (3 == sscanf(s,
                "%*[^0123456789]%d%*[^0123456789]%d%*[^0123456789]%d",
                &i1,
                &i2,
                &i3))
{
    printf("%d %d %d\n", i1, i2, i3);
}

where %*[^0123456789] means ignore input until a digit is found. See demo at http://ideone.com/2hB4UW .

Or, if the number of numbers is unknown you can use %n specifier to record the last position read in the buffer:

const char* s = "ab234cid*(s349*(20kd";
int total_n = 0;
int n;
int i;
while (1 == sscanf(s + total_n, "%*[^0123456789]%d%n", &i, &n))
{
    total_n += n;
    printf("%d\n", i);
}

How to make vim paste from (and copy to) system's clipboard?

On top of the setting :set clipboard=unnamed, you should use mvim -v which you can get with brew install macvim if you're using vim on Terminal.app on Mac OS X 10.9. Default vim does not support clipboard option.

How to make the script wait/sleep in a simple way in unity

With .Net 4.x you can use Task-based Asynchronous Pattern (TAP) to achieve this:

// .NET 4.x async-await
using UnityEngine;
using System.Threading.Tasks;
public class AsyncAwaitExample : MonoBehaviour
{
     private async void Start()
     {
        Debug.Log("Wait.");
        await WaitOneSecondAsync();
        DoMoreStuff(); // Will not execute until WaitOneSecond has completed
     }
    private async Task WaitOneSecondAsync()
    {
        await Task.Delay(TimeSpan.FromSeconds(1));
        Debug.Log("Finished waiting.");
    }
}

this is a feature to use .Net 4.x with Unity please see this link for description about it

and this link for sample project and compare it with coroutine

But becareful as documentation says that This is not fully replacement with coroutine

Add and remove a class on click using jQuery?

You can do this:-

$('#about-link').addClass('current');
$('#menu li a').on('click', function(e){
    e.preventDefault();
    $('#menu li a.current').removeClass('current');
    $(this).addClass('current');
});

Demo: Fiddle

Insert some string into given string at given index in Python

There are several ways to do this:

One way is to use slicing:

>>> a="line=Name Age Group Class Profession"
>>> b=a.split()
>>> b[2:2]=[b[2]]*3
>>> b
['line=Name', 'Age', 'Group', 'Group', 'Group', 'Group', 'Class', 'Profession']
>>> a=" ".join(b)
>>> a
'line=Name Age Group Group Group Group Class Profession'

Another would be to use regular expressions:

>>> import re
>>> a=re.sub(r"(\S+\s+\S+\s+)(\S+\s+)(.*)", r"\1\2\2\2\2\3", a)
>>> a
'line=Name Age Group Group Group Group Class Profession'

What is an MvcHtmlString and when should I use it?

A nice practical use of this is if you want to make your own HtmlHelper extensions. For example, I hate trying to remember the <link> tag syntax, so I've created my own extension method to make a <link> tag:

<Extension()> _
Public Function CssBlock(ByVal html As HtmlHelper, ByVal src As String, ByVal Optional ByVal htmlAttributes As Object = Nothing) As MvcHtmlString
    Dim tag = New TagBuilder("link")
    tag.MergeAttribute("type", "text/css")
    tag.MergeAttribute("rel", "stylesheet")
    tag.MergeAttribute("href", src)
    tag.MergeAttributes(New RouteValueDictionary(htmlAttributes))
    Dim result = tag.ToString(TagRenderMode.Normal)
    Return MvcHtmlString.Create(result)
End Function

I could have returned String from this method, but if I had the following would break:

<%: Html.CssBlock(Url.Content("~/sytles/mysite.css")) %>

With MvcHtmlString, using either <%: ... %> or <%= ... %> will both work correctly.

Android Camera Preview Stretched

NOTE: MY SOLUTION IS A CONTINUATION OF HESAM'S SOLUTION: https://stackoverflow.com/a/22758359/1718734

What I address: Hesam's said there is a little white space that may appear on some phones, like this:

NOTE: Although the aspect ratio is correct, the camera does not fill in the whole screen.

Hesam suggested a second solution, but that squishes the preview. And on some devices, it heavily distorts.

So how do we fix this problem. It is simple...by multiplying the aspect ratios till it fills in the screen. I have noticed, several popular apps such as Snapchat, WhatsApp, etc works the same way.

All you have to do is add this to the onMeasure method:

float camHeight = (int) (width * ratio);
    float newCamHeight;
    float newHeightRatio;

    if (camHeight < height) {
        newHeightRatio = (float) height / (float) mPreviewSize.height;
        newCamHeight = (newHeightRatio * camHeight);
        Log.e(TAG, camHeight + " " + height + " " + mPreviewSize.height + " " + newHeightRatio + " " + newCamHeight);
        setMeasuredDimension((int) (width * newHeightRatio), (int) newCamHeight);
        Log.e(TAG, mPreviewSize.width + " | " + mPreviewSize.height + " | ratio - " + ratio + " | H_ratio - " + newHeightRatio + " | A_width - " + (width * newHeightRatio) + " | A_height - " + newCamHeight);
    } else {
        newCamHeight = camHeight;
        setMeasuredDimension(width, (int) newCamHeight);
        Log.e(TAG, mPreviewSize.width + " | " + mPreviewSize.height + " | ratio - " + ratio + " | A_width - " + (width) + " | A_height - " + newCamHeight);
    }

This will calculate the screen height and gets the ratio of the screen height and the mPreviewSize height. Then it multiplies the camera's width and height by the new height ratio and the set the measured dimension accordingly.

enter image description here

And the next thing you know, you end up with this :D

enter image description here

This also works well with he front camera. I believe this is the best way to go about this. Now the only thing left for my app is to save the preview itself upon clicking on "Capture." But ya, this is it.

PostgreSQL CASE ... END with multiple conditions

This kind of code perhaps should work for You

SELECT
 *,
 CASE
  WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
  ELSE '00'
 END AS modifiedpvc
FROM my_table;


 gid | datepose | pvc | modifiedpvc 
-----+----------+-----+-------------
   1 |     1961 | 01  | 00
   2 |     1949 |     | 01
   3 |     1990 | 02  | 00
   1 |     1981 |     | 02
   1 |          | 03  | 00
   1 |          |     | 03
(6 rows)

How to make borders collapse (on a div)?

Example of using border-collapse: separate; as

  • container displayed as table:

    ol[type="I"]>li{
      display: table;
      border-collapse: separate;
      border-spacing: 1rem;
    }
    
  • C++ queue - simple example

    std::queue<myclass*> that's it

    In Python, how to check if a string only contains certain characters?

    Simpler approach? A little more Pythonic?

    >>> ok = "0123456789abcdef"
    >>> all(c in ok for c in "123456abc")
    True
    >>> all(c in ok for c in "hello world")
    False
    

    It certainly isn't the most efficient, but it's sure readable.

    Address already in use: JVM_Bind java

    I usually come across this when the port which the server (I use JBoss) is already in use

    Usual suspects

    1. Apache Http Server => turn down the service if working in windows.
    2. IIS => stop the ISS using
    3. Skype =>yea I got skype attaching itself to port 80

    To change the port to which JBoss 4.2.x binds itself go to:

    "C:\jboss4.2.2\server\default\deploy\jboss-web.deployer\server.xml"

    here default is the instance of the server change the port here :

    <Connector port="8080" address="${jboss.bind.address}" >

    In the above example the port is bound to 8080

    jQuery Set Cursor Position in Text Area

    I do realize that this is a very old post, but I thought that I should offer perhaps a simpler solution to update it using only jQuery.

    function getTextCursorPosition(ele) {   
        return ele.prop("selectionStart");
    }
    
    function setTextCursorPosition(ele,pos) {
        ele.prop("selectionStart", pos + 1);
        ele.prop("selectionEnd", pos + 1);
    }
    
    function insertNewLine(text,cursorPos) {
        var firstSlice = text.slice(0,cursorPos);
        var secondSlice = text.slice(cursorPos);
    
        var new_text = [firstSlice,"\n",secondSlice].join('');
    
        return new_text;
    }
    

    Usage for using ctrl-enter to add a new line (like in Facebook):

    $('textarea').on('keypress',function(e){
        if (e.keyCode == 13 && !e.ctrlKey) {
            e.preventDefault();
            //do something special here with just pressing Enter
        }else if (e.ctrlKey){
            //If the ctrl key was pressed with the Enter key,
            //then enter a new line break into the text
            var cursorPos = getTextCursorPosition($(this));                
    
            $(this).val(insertNewLine($(this).val(), cursorPos));
            setTextCursorPosition($(this), cursorPos);
        }
    });
    

    I am open to critique. Thank you.

    UPDATE: This solution does not allow normal copy and paste functionality to work (i.e. ctrl-c, ctrl-v), so I will have to edit this in the future to make sure that part works again. If you have an idea how to do that, please comment here, and I will be happy to test it out. Thanks.

    Visual Studio 2010 - recommended extensions

    1. Plugin to quickly go to any file in solution Sonic file finder (free)

    2. Fast switching between .h and .cpp file Macro available here (free)

    And that's it =)

    How to git commit a single file/directory

    Try:

    git commit -m 'my notes' path/to/my/file.ext 
    

    How to dynamically create generic C# object using reflection?

    Make sure you're doing this for a good reason, a simple function like the following would allow static typing and allows your IDE to do things like "Find References" and Refactor -> Rename.

    public Task <T> factory (String name)
    {
      Task <T> result;
    
      if (name.CompareTo ("A") == 0)
      {
        result = new TaskA ();
      }
      else if (name.CompareTo ("B") == 0)
      {
        result = new TaskB ();
      }
    
      return result;
    }
    

    How to update column value in laravel

    Version 1:

    // Update data of question values with $data from formulay
    $Q1 = Question::find($id);
    $Q1->fill($data);
    $Q1->push();
    

    Version 2:

    $Q1 = Question::find($id);
    $Q1->field = 'YOUR TEXT OR VALUE';
    $Q1->save();
    

    In case of answered question you can use them:

    $page = Page::find($id);
    $page2update = $page->where('image', $path);
    $page2update->image = 'IMGVALUE';
    $page2update->save();
    

    Pandas (python): How to add column to dataframe for index?

    How about this:

    from pandas import *
    
    idx = Int64Index([171, 174, 173])
    df = DataFrame(index = idx, data =([1,2,3]))
    print df
    

    It gives me:

         0
    171  1
    174  2
    173  3
    

    Is this what you are looking for?

    Android: how to get the current day of the week (Monday, etc...) in the user's language?

    //selected date from calender
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy"); //Date and time
    String currentDate = sdf.format(myCalendar.getTime());
    
    //selcted_day name
    SimpleDateFormat sdf_ = new SimpleDateFormat("EEEE");
    String dayofweek=sdf_.format(myCalendar.getTime());
    current_date.setText(currentDate);
    lbl_current_date.setText(dayofweek);
    
    Log.e("dayname", dayofweek);
    

    Check if a string has a certain piece of text

    Here you go: ES5

    var test = 'Hello World';
    if( test.indexOf('World') >= 0){
      // Found world
    }
    

    With ES6 best way would be to use includes function to test if the string contains the looking work.

    const test = 'Hello World';
    if (test.includes('World')) { 
      // Found world
    }
    

    Body set to overflow-y:hidden but page is still scrollable in Chrome

    Ok so this is the combination that worked for me when I had this problem on one of my websites:

    html {
        height: 100%;
    }
    
    body {
        overflow-x: hidden;
    }
    

    Java OCR implementation

    There are a variety of OCR libraries out there. However, my experience is that the major commercial implementations, ABBYY, Omnipage, and ReadIris, far outdo the open-source or other minor implementations. These commercial libraries are not primarily designed to work with Java, though of course it is possible.

    Of course, if your interest is to learn the code, the open-source implementations will do the trick.

    Get name of current script in Python

    You can do this without importing os or other libs.

    If you want to get the path of current python script, use: __file__

    If you want to get only the filename without .py extension, use this:

    __file__.rsplit("/", 1)[1].split('.')[0]
    

    Find size of an array in Perl

    To use the second way, add 1:

    print $#arr + 1; # Second way to print array size
    

    How do I make the method return type generic?

    I did the following in my lib kontraktor:

    public class Actor<SELF extends Actor> {
        public SELF self() { return (SELF)_self; }
    }
    

    subclassing:

    public class MyHttpAppSession extends Actor<MyHttpAppSession> {
       ...
    }
    

    at least this works inside the current class and when having a strong typed reference. Multiple inheritance works, but gets really tricky then :)

    How to reduce the image size without losing quality in PHP

    well I think I have something interesting for you... https://github.com/whizzzkid/phpimageresize. I wrote it for the exact same purpose. Highly customizable, and does it in a great way.

    Python script to copy text to clipboard

    On macOS, use subprocess.run to pipe your text to pbcopy:

    import subprocess 
    data = "hello world"
    subprocess.run("pbcopy", universal_newlines=True, input=data)
    

    It will copy "hello world" to the clipboard.

    Bootstrap Align Image with text

    I think this is helpful for you

    <div class="container">
            <div class="page-header">
                    <h1>About Me</h1>
                </div><!--END page-header-->
            <div class="row" id="features">
                    <div class="col-sm-6 feature">
                            <img src="http://lorempixel.com/200/200" alt="Web Design" class="img-circle">
                    </div><!--END feature-->
    
                    <div class="col-sm-6 feature">
                            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,</p>
                    </div><!--END feature-->
                </div><!--end features-->
        </div><!--end container-->
    

    Why do I have to define LD_LIBRARY_PATH with an export every time I run my application?

    Use

    export LD_LIBRARY_PATH="/path/to/library/"
    

    in your .bashrc otherwise, it'll only be available to bash and not any programs you start.

    Try -R/path/to/library/ flag when you're linking, it'll make the program look in that directory and you won't need to set any environment variables.

    EDIT: Looks like -R is Solaris only, and you're on Linux.

    An alternate way would be to add the path to /etc/ld.so.conf and run ldconfig. Note that this is a global change that will apply to all dynamically linked binaries.

    Improve INSERT-per-second performance of SQLite

    Try using SQLITE_STATIC instead of SQLITE_TRANSIENT for those inserts.

    SQLITE_TRANSIENT will cause SQLite to copy the string data before returning.

    SQLITE_STATIC tells it that the memory address you gave it will be valid until the query has been performed (which in this loop is always the case). This will save you several allocate, copy and deallocate operations per loop. Possibly a large improvement.

    IntelliJ IDEA 13 uses Java 1.5 despite setting to 1.7

    I had the following property working for me in IntelliJ 2017

      <properties>
            <java.version>1.8</java.version>       
      </properties>
    

    PHP passing $_GET in linux command prompt

    From this answer on ServerFault:

    Use the php-cgi binary instead of just php, and pass the arguments on the command line, like this:

    php-cgi -f index.php left=1058 right=1067 class=A language=English
    

    Which puts this in $_GET:

    Array
    (
        [left] => 1058
        [right] => 1067
        [class] => A
        [language] => English
    )
    

    You can also set environment variables that would be set by the web server, like this:

    REQUEST_URI='/index.php' SCRIPT_NAME='/index.php' php-cgi -f index.php left=1058 right=1067 class=A language=English
    

    How to select the last record of a table in SQL?

    If you have a self-incrementing field (say ID) then you can do something like: SELECT * FROM foo WHERE ID = (SELECT max(ID) FROM foo)

    How can I see which Git branches are tracking which remote / upstream branch?

    I use this alias

    git config --global alias.track '!f() { ([ $# -eq 2 ] && ( echo "Setting tracking for branch " $1 " -> " $2;git branch --set-upstream $1 $2; ) || ( git for-each-ref --format="local: %(refname:short) <--sync--> remote: %(upstream:short)" refs/heads && echo --Remotes && git remote -v)); }; f'
    

    then

    git track
    

    Prevent Bootstrap Modal from disappearing when clicking outside or pressing escape?

    You can use the code below

    $.fn.modal.prototype.constructor.Constructor.DEFAULTS.backdrop = 'static';
    

    to change the default behavior.

    How to add `style=display:"block"` to an element using jQuery?

    If you need to add multiple then you can do it like this:

    $('#element').css({
        'margin-left': '5px',
        'margin-bottom': '-4px',
        //... and so on
    });
    

    As a good practice I would also put the property name between quotes to allow the dash since most styles have a dash in them. If it was 'display', then quotes are optional but if you have a dash, it will not work without the quotes. Anyways, to make it simple: always enclose them in quotes.

    Can HTTP POST be limitless?

    Different IIS web servers can process different amounts of data in the 'header', according to this (now deleted) article; http://classicasp.aspfaq.com/forms/what-is-the-limit-on-form/post-parameters.html;

    Note that there is no limit on the number of FORM elements you can pass via POST, but only on the aggregate size of all name/value pairs. While GET is limited to as low as 1024 characters, POST data is limited to 2 MB on IIS 4.0, and 128 KB on IIS 5.0. Each name/value is limited to 1024 characters, as imposed by the SGML spec. Of course this does not apply to files uploaded using enctype='multipart/form-data' ... I have had no problems uploading files in the 90 - 100 MB range using IIS 5.0, aside from having to increase the server.scriptTimeout value as well as my patience!

    Nodejs convert string into UTF-8

    I'd recommend using the Buffer class:

    var someEncodedString = Buffer.from('someString', 'utf-8');
    

    This avoids any unnecessary dependencies that other answers require, since Buffer is included with node.js, and is already defined in the global scope.

    How to get N rows starting from row M from sorted table in T-SQL

    Find id for row N Then get the top M rows that have an id greater than or equal to that

    declare @N as int
    set @N = 2
    declare @M as int
    set @M = 3
    
    declare @Nid as int
    
    set @Nid = max(id)
    from
      (select top @N *
    from MyTable
    order by id)
    
    select top @M *
    from MyTable
    where id >= @Nid
    order by id
    

    Something like that ... but I've made some assumptions here (e.g. you want to order by id)

    How to run Linux commands in Java?

    You can use java.lang.Runtime.exec to run simple code. This gives you back a Process and you can read its standard output directly without having to temporarily store the output on disk.

    For example, here's a complete program that will showcase how to do it:

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    
    public class testprog {
        public static void main(String args[]) {
            String s;
            Process p;
            try {
                p = Runtime.getRuntime().exec("ls -aF");
                BufferedReader br = new BufferedReader(
                    new InputStreamReader(p.getInputStream()));
                while ((s = br.readLine()) != null)
                    System.out.println("line: " + s);
                p.waitFor();
                System.out.println ("exit: " + p.exitValue());
                p.destroy();
            } catch (Exception e) {}
        }
    }
    

    When compiled and run, it outputs:

    line: ./
    line: ../
    line: .classpath*
    line: .project*
    line: bin/
    line: src/
    exit: 0
    

    as expected.

    You can also get the error stream for the process standard error, and output stream for the process standard input, confusingly enough. In this context, the input and output are reversed since it's input from the process to this one (i.e., the standard output of the process).

    If you want to merge the process standard output and error from Java (as opposed to using 2>&1 in the actual command), you should look into ProcessBuilder.

    How to show/hide if variable is null

    In this case, myvar should be a boolean value. If this variable is true, it will show the div, if it's false.. It will hide.

    Check this out.

    Finding repeated words on a string and counting the repetitions

    For Strings with no space, we can use the below mentioned code

    private static void findRecurrence(String input) {
        final Map<String, Integer> map = new LinkedHashMap<>();
        for(int i=0; i<input.length(); ) {
            int pointer = i;
            int startPointer = i;
            boolean pointerHasIncreased = false;
            for(int j=0; j<startPointer; j++){
                if(pointer<input.length() && input.charAt(j)==input.charAt(pointer) && input.charAt(j)!=32){
                    pointer++;
                    pointerHasIncreased = true;
                }else{
                    if(pointerHasIncreased){
                        break;
                    }
                }
            }
            if(pointer - startPointer >= 2) {
                String word = input.substring(startPointer, pointer);
                if(map.containsKey(word)){
                    map.put(word, map.get(word)+1);
                }else{
                    map.put(word, 1);
                }
                i=pointer;
            }else{
                i++;
            }
        }
        for(Map.Entry<String, Integer> entry : map.entrySet()){
            System.out.println(entry.getKey() + " = " + (entry.getValue()+1));
        }
    }
    

    Passing some input as "hahaha" or "ba na na" or "xxxyyyzzzxxxzzz" give the desired output.

    How can I prevent the backspace key from navigating back?

    I had some problems with the accepted solution and the Select2.js plugin; I was not able to delete characters in the editable box as the delete action was being prevented. This was my solution:

    //Prevent backwards navigation when trying to delete disabled text.
    $(document).unbind('keydown').bind('keydown', function (event) {
    
        if (event.keyCode === 8) {
    
            var doPrevent = false,
                d = event.srcElement || event.target,
                tagName = d.tagName.toUpperCase(),
                type = (d.type ? d.type.toUpperCase() : ""),
                isEditable = d.contentEditable,
                isReadOnly = d.readOnly,
                isDisabled = d.disabled;
    
            if (( tagName === 'INPUT' && (type === 'TEXT' || type === 'PASSWORD'))
                || tagName === 'PASSWORD'
                || tagName === 'TEXTAREA') {
                doPrevent =  isReadOnly || isDisabled;
            }
            else if(tagName === 'SPAN'){
                doPrevent = !isEditable;
            }
            else {
                doPrevent = true;
            }
        }
    
        if (doPrevent) {
            event.preventDefault();
        }
    });
    

    Select2 creates a Span with an attribute of "contentEditable" which is set to true for the editable combo box in it. I added code to account for the spans tagName and the different attribute. This solved all my problems.

    Edit: If you are not using the Select2 combobox plugin for jquery, then this solution may not be needed by you, and the accepted solution might be better.

    jQuery - how to check if an element exists?

    if ($("#MyId").length) { ... write some code here ...}
    

    This from will automatically check for the presence of the element and will return true if an element exists.

    Multiple condition in single IF statement

    Yes that is valid syntax but it may well not do what you want.

    Execution will continue after your RAISERROR except if you add a RETURN. So you will need to add a block with BEGIN ... END to hold the two statements.

    Also I'm not sure why you plumped for severity 15. That usually indicates a syntax error.

    Finally I'd simplify the conditions using IN

    CREATE PROCEDURE [dbo].[AddApplicationUser] (@TenantId BIGINT,
                                                @UserType TINYINT,
                                                @UserName NVARCHAR(100),
                                                @Password NVARCHAR(100))
    AS
      BEGIN
          IF ( @TenantId IS NULL
               AND @UserType IN ( 0, 1 ) )
            BEGIN
                RAISERROR('The value for @TenantID should not be null',15,1);
    
                RETURN;
            END
      END 
    

    Remove rows not .isin('X')

    You can use numpy.logical_not to invert the boolean array returned by isin:

    In [63]: s = pd.Series(np.arange(10.0))
    
    In [64]: x = range(4, 8)
    
    In [65]: mask = np.logical_not(s.isin(x))
    
    In [66]: s[mask]
    Out[66]: 
    0    0
    1    1
    2    2
    3    3
    8    8
    9    9
    

    As given in the comment by Wes McKinney you can also use

    s[~s.isin(x)]
    

    Purpose of Activator.CreateInstance with example?

    Why would you use it if you already knew the class and were going to cast it? Why not just do it the old fashioned way and make the class like you always make it? There's no advantage to this over the way it's done normally. Is there a way to take the text and operate on it thusly:

    label1.txt = "Pizza" 
    Magic(label1.txt) p = new Magic(lablel1.txt)(arg1, arg2, arg3);
    p.method1();
    p.method2();
    

    If I already know its a Pizza there's no advantage to:

    p = (Pizza)somefancyjunk("Pizza"); over
    Pizza p = new Pizza();
    

    but I see a huge advantage to the Magic method if it exists.

    Reasons for a 409/Conflict HTTP error when uploading a file to sharepoint using a .NET WebRequest?

    We are also getting the same error while we are trying to access a same resource with in milliseconds. Like if i try to POST some data to www.abc.com/blog and with in milliseconds an other request will also go for the same resource i.e. www.abc.com/blog from the same user. So it'll give the 409 error.

    Convert string to variable name in JavaScript

    let me make it more clear

    function changeStringToVariable(variable, value){
    window[variable]=value
    }
    changeStringToVariable("name", "john doe");
    console.log(name);
    //this outputs: john doe
    let file="newFile";
    changeStringToVariable(file, "text file");
    console.log(newFile);
    //this outputs: text file
    

    Find OpenCV Version Installed on Ubuntu

    The other methods here didn't work for me, so here's what does work in Ubuntu 12.04 'precise'.

    On Ubuntu and other Debian-derived platforms, dpkg is the typical way to get software package versions. For more recent versions than the one that @Tio refers to, use

     dpkg -l | grep libopencv
    

    If you have the development packages installed, like libopencv-core-dev, you'll probably have .pc files and can use pkg-config:

     pkg-config --modversion opencv
    

    Android soft keyboard covers EditText field

    I had the same issue where the softkeyboard was on top of the EditText views which were placed on the bottom of the screen. I was able to find a solution by adding a single line to my AndroidManifest.xml file's relevant activity.

    android:windowSoftInputMode="adjustResize|stateHidden"
    

    This is how the whole activity tag looks like:

    <activity
            android:name="com.my.MainActivity"
            android:screenOrientation="portrait"
            android:label="@string/title_activity_main"
            android:windowSoftInputMode="adjustResize|stateHidden" >
        </activity>
    

    Here the most important value is the adjustResize. This will shift the whole UI up to give room for the softkeyboard.

    How can I initialize C++ object member variables in the constructor?

    I know this is 5 years later, but the replies above don't address what was wrong with your software. (Well, Yuushi's does, but I didn't realise until I had typed this - doh!). They answer the question in the title How can I initialize C++ object member variables in the constructor? This is about the other questions: Am I using the right approach but the wrong syntax? Or should I be coming at this from a different direction?

    Programming style is largely a matter of opinion, but an alternative view to doing as much as possible in a constructor is to keep constructors down to a bare minimum, often having a separate initialization function. There is no need to try to cram all initialization into a constructor, never mind trying to force things at times into the constructors initialization list.

    So, to the point, what was wrong with your software?

    private:
        ThingOne* ThingOne;
        ThingTwo* ThingTwo;
    

    Note that after these lines, ThingOne (and ThingTwo) now have two meanings, depending on context.

    Outside of BigMommaClass, ThingOne is the class you created with #include "ThingOne.h"

    Inside BigMommaClass, ThingOne is a pointer.

    That is assuming the compiler can even make sense of the lines and doesn't get stuck in a loop thinking that ThingOne is a pointer to something which is itself a pointer to something which is a pointer to ...

    Later, when you write

    this->ThingOne = ThingOne(100);
    this->ThingTwo = ThingTwo(numba1, numba2);
    

    bear in mind that inside of BigMommaClass your ThingOne is a pointer.

    If you change the declarations of the pointers to include a prefix (p)

    private:
        ThingOne* pThingOne;
        ThingTwo* pThingTwo;
    

    Then ThingOne will always refer to the class and pThingOne to the pointer.

    It is then possible to rewrite

    this->ThingOne = ThingOne(100);
    this->ThingTwo = ThingTwo(numba1, numba2);
    

    as

    pThingOne = new ThingOne(100);
    pThingTwo = new ThingTwo(numba1, numba2);
    

    which corrects two problems: the double meaning problem, and the missing new. (You can leave this-> if you like!)

    With that in place, I can add the following lines to a C++ program of mine and it compiles nicely.

    class ThingOne{public:ThingOne(int n){};};
    class ThingTwo{public:ThingTwo(int x, int y){};};
    
    class BigMommaClass {
    
        public:
                BigMommaClass(int numba1, int numba2);
    
        private:
                ThingOne* pThingOne;
                ThingTwo* pThingTwo;
    };
    
    BigMommaClass::BigMommaClass(int numba1, int numba2)
    {
        pThingOne = new ThingOne(numba1 + numba2);
        pThingTwo = new ThingTwo(numba1, numba2);
    };
    

    When you wrote

    this->ThingOne = ThingOne(100);
    this->ThingTwo = ThingTwo(numba1, numba2);
    

    the use of this-> tells the compiler that the left hand side ThingOne is intended to mean the pointer. However we are inside BigMommaClass at the time and it's not necessary.

    The problem is with the right hand side of the equals where ThingOne is intended to mean the class. So another way to rectify your problems would have been to write

    this->ThingOne = new ::ThingOne(100);
    this->ThingTwo = new ::ThingTwo(numba1, numba2);
    

    or simply

    ThingOne = new ::ThingOne(100);
    ThingTwo = new ::ThingTwo(numba1, numba2);
    

    using :: to change the compiler's interpretation of the identifier.

    How can I make a button redirect my page to another page?

    This is here:

     <button onClick="window.location='page_name.php';" value="click here" />
    

    Change variable name in for loop using R

    d <- 5
    for(i in 1:10) { 
     nam <- paste("A", i, sep = "")
     assign(nam, rnorm(3)+d)
    }
    

    More info here or even here!

    Java: Local variable mi defined in an enclosing scope must be final or effectively final

    Yes this is happening because you are accessing mi variable from within your anonymous inner class, what happens deep inside is that another copy of your variable is created and will be use inside the anonymous inner class, so for data consistency the compiler will try restrict you from changing the value of mi so that's why its telling you to set it to final.

    HTTP POST with URL query parameters -- good idea or not?

    It would be fine to use query parameters on a POST endpoint, provided they refer to already existing resources.

    For example:

    POST /user_settings?user_id=4
    {
      "use_safe_mode": 1
    }
    

    The POST above has a query parameter referring to an existing resource. The body parameter defines the new resource to be created.

    (Granted, this may be more of a personal preference than a dogmatic principle.)

    When to use dynamic vs. static libraries

    We use a lot of DLL's (> 100) in our project. These DLL's have dependencies on each other and therefore we chose the setup of dynamic linking. However it has the following disadvantages:

    • slow startup (> 10 seconds)
    • DLL's had to be versioned, since windows loads modules on uniqueness of names. Own written components would otherwise get the wrong version of the DLL (i.e. the one already loaded instead of its own distributed set)
    • optimizer can only optimize within DLL boundaries. For example the optimizer tries to place frequently used data and code next to each other, but this will not work across DLL boundaries

    Maybe a better setup was to make everything a static library (and therefore you just have one executable). This works only if no code duplication takes place. A test seems to support this assumption, but i couldn't find an official MSDN quote. So for example make 1 exe with:

    • exe uses shared_lib1, shared_lib2
    • shared_lib1 use shared_lib2
    • shared_lib2

    The code and variables of shared_lib2 should be present in the final merged executable only once. Can anyone support this question?

    Rename file with Git

    You've got "Bad Status" its because the target file cannot find or not present, like for example you call README file which is not in the current directory.

    In Angular, how to pass JSON object/array into directive?

    If you want to follow all the "best practices," there's a few things I'd recommend, some of which are touched on in other answers and comments to this question.


    First, while it doesn't have too much of an affect on the specific question you asked, you did mention efficiency, and the best way to handle shared data in your application is to factor it out into a service.

    I would personally recommend embracing AngularJS's promise system, which will make your asynchronous services more composable compared to raw callbacks. Luckily, Angular's $http service already uses them under the hood. Here's a service that will return a promise that resolves to the data from the JSON file; calling the service more than once will not cause a second HTTP request.

    app.factory('locations', function($http) {
      var promise = null;
    
      return function() {
        if (promise) {
          // If we've already asked for this data once,
          // return the promise that already exists.
          return promise;
        } else {
          promise = $http.get('locations/locations.json');
          return promise;
        }
      };
    });
    

    As far as getting the data into your directive, it's important to remember that directives are designed to abstract generic DOM manipulation; you should not inject them with application-specific services. In this case, it would be tempting to simply inject the locations service into the directive, but this couples the directive to that service.

    A brief aside on code modularity: a directive’s functions should almost never be responsible for getting or formatting their own data. There’s nothing to stop you from using the $http service from within a directive, but this is almost always the wrong thing to do. Writing a controller to use $http is the right way to do it. A directive already touches a DOM element, which is a very complex object and is difficult to stub out for testing. Adding network I/O to the mix makes your code that much more difficult to understand and that much more difficult to test. In addition, network I/O locks in the way that your directive will get its data – maybe in some other place you’ll want to have this directive receive data from a socket or take in preloaded data. Your directive should either take data in as an attribute through scope.$eval and/or have a controller to handle acquiring and storing the data.

    - The 80/20 Guide to Writing AngularJS Directives

    In this specific case, you should place the appropriate data on your controller's scope and share it with the directive via an attribute.

    app.controller('SomeController', function($scope, locations) {
      locations().success(function(data) {
        $scope.locations = data;
      });
    });
    
    <ul class="list">
       <li ng-repeat="location in locations">
          <a href="#">{{location.id}}. {{location.name}}</a>
       </li>
    </ul>
    <map locations='locations'></map>
    
    app.directive('map', function() {
      return {
        restrict: 'E',
        replace: true,
        template: '<div></div>',
        scope: {
          // creates a scope variable in your directive
          // called `locations` bound to whatever was passed
          // in via the `locations` attribute in the DOM
          locations: '=locations'
        },
        link: function(scope, element, attrs) {
          scope.$watch('locations', function(locations) {
            angular.forEach(locations, function(location, key) {
              // do something
            });
          });
        }
      };
    });
    

    In this way, the map directive can be used with any set of location data--the directive is not hard-coded to use a specific set of data, and simply linking the directive by including it in the DOM will not fire off random HTTP requests.

    " netsh wlan start hostednetwork " command not working no matter what I try

    If none of the above solution worked for you, locate the Wifi adapter from "Control Panel\Network and Internet\Network Connections", right click on it, and select "Diagnose", then follow the given instructions on the screen. It worked for me.

    How do I upgrade to Python 3.6 with conda?

    This is how I mange to get (as currently there is no direct support- in future it will be for sure) python 3.9 in anaconda and windows 10
    Note: I needed extra packages so install them, install only what you need

    conda create --name e39 python=3.9 --channel conda-forge
    

    Equivalent of Super Keyword in C#

    C# equivalent of your code is

      class Imagedata : PDFStreamEngine
      {
         // C# uses "base" keyword whenever Java uses "super" 
         // so instead of super(...) in Java we should call its C# equivalent (base):
         public Imagedata()
           : base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true)) 
         { }
    
         // Java methods are virtual by default, when C# methods aren't.
         // So we should be sure that processOperator method in base class 
         // (that is PDFStreamEngine)
         // declared as "virtual"
         protected override void processOperator(PDFOperator operations, List arguments)
         {
            base.processOperator(operations, arguments);
         }
      }
    

    Calculate last day of month in JavaScript

    I recently had to do something similar, this is what I came up with:

    /**
    * Returns a date set to the begining of the month
    * 
    * @param {Date} myDate 
    * @returns {Date}
    */
    function beginningOfMonth(myDate){    
      let date = new Date(myDate);
      date.setDate(1)
      date.setHours(0);
      date.setMinutes(0);
      date.setSeconds(0);   
      return date;     
    }
    
    /**
     * Returns a date set to the end of the month
     * 
     * @param {Date} myDate 
     * @returns {Date}
     */
    function endOfMonth(myDate){
      let date = new Date(myDate);
      date.setMonth(date.getMonth() +1)
      date.setDate(0);
      date.setHours(23);
      date.setMinutes(59);
      date.setSeconds(59);
      return date;
    }
    

    Pass it in a date, and it will return a date set to either the beginning of the month, or the end of the month.

    The begninngOfMonth function is fairly self-explanatory, but what's going in in the endOfMonth function is that I'm incrementing the month to the next month, and then using setDate(0) to roll back the day to the last day of the previous month which is a part of the setDate spec:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate https://www.w3schools.com/jsref/jsref_setdate.asp

    I then set the hour/minutes/seconds to the end of the day, so that if you're using some kind of API that is expecting a date range you'll be able to capture the entirety of that last day. That part might go beyond what the original post is asking for but it could help someone else looking for a similar solution.

    Edit: You can also go the extra mile and set milliseconds with setMilliseconds() if you want to be extra precise.

    How do I access Configuration in any class in ASP.NET Core?

    There is also an option to make configuration static in startup.cs so that what you can access it anywhere with ease, static variables are convenient huh!

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
    
    internal static IConfiguration Configuration { get; private set; }
    

    This makes configuration accessible anywhere using Startup.Configuration.GetSection... What can go wrong?

    Stash only one file out of multiple files that have changed with Git?

    I would use git stash save --patch. I don't find the interactivity to be annoying because there are options during it to apply the desired operation to entire files.

    Android Activity without ActionBar

    If you want most of your activities to have an action bar you would probably inherit your base theme from the default one (this is automatically generated by Android Studio per default):

    <!-- Base application theme. -->
        <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
            <!-- Customize your theme here. -->
            <item name="colorPrimary">@color/colorPrimary</item>
            <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
            <item name="colorAccent">@color/colorAccent</item>
        </style>
    

    And then add a special theme for your bar-less activity:

    <style name="AppTheme.NoTitle" parent="AppTheme">
            <item name="windowNoTitle">true</item>
            <item name="windowActionBar">false</item>
            <item name="actionBarTheme">@null</item>
        </style>
    

    For me, setting actionBarTheme to @null was the solution.

    Finally setup the activity in your manifest file:

    <activity ... android:theme="@style/AppTheme.NoTitle" ... >
    

    How to get these two divs side-by-side?

    Using flexbox

       #parent_div_1{
         display:flex;
         flex-wrap: wrap;
      }
    

    duplicate 'row.names' are not allowed error

    This related question points out a part of the ?read.table documentation that explains your problem:

    If there is a header and the first row contains one fewer field than the number of columns, the first column in the input is used for the row names. Otherwise if row.names is missing, the rows are numbered.

    Your header row likely has 1 fewer column than the rest of the file and so read.table assumes that the first column is the row.names (which must all be unique), not a column (which can contain duplicated values). You can fix this by using one of the following two Solutions:

    1. adding a delimiter (ie \t or ,) to the front or end of your header row in the source file, or,
    2. removing any trailing delimiters in your data

    The choice will depend on the structure of your data.

    Example:
    Here the header row is interpreted as having one fewer column than the data because the delimiters don't match:

    v1,v2,v3   # 3 items!!
    a1,a2,a3,  # 4 items
    b1,b2,b3,  # 4 items
    

    This is how it is interpreted by default:

       v1,v2,v3   # 3 items!!
    a1,a2,a3,  # 4 items
    b1,b2,b3,  # 4 items
    

    The first column (with no header) values are interpreted as row.names: a1 and b1. If this column contains duplicates, which is entirely possible, then you get the duplicate 'row.names' are not allowed error.

    If you set row.names = FALSE, the shift doesn't happen, but you still have a mismatching number of items in the header and in the data because the delimiters don't match.

    Solution 1 Add trailing delimiter to header:

    v1,v2,v3,  # 4 items!!
    a1,a2,a3,  # 4 items
    b1,b2,b3,  # 4 items
    

    Solution 2 Remove excess trailing delimiter from non-header rows:

    v1,v2,v3   # 3 items
    a1,a2,a3   # 3 items!!
    b1,b2,b3   # 3 items!!
    

    How do I ignore a directory with SVN?

    TO KEEP DIRECTORIES THAT SVN WILL IGNORE:

    1. this will delete the files from the repository, but keep the directory under SVN control:

    svn delete --keep-local path/directory_to_keep/*

    1. then set to ignore the directory (and all content):

    svn propset svn:ignore "*" path/directory_to_keep

    Check if my SSL Certificate is SHA1 or SHA2

    You can check by visiting the site in your browser and viewing the certificate that the browser received. The details of how to do that can vary from browser to browser, but generally if you click or right-click on the lock icon, there should be an option to view the certificate details.

    In the list of certificate fields, look for one called "Certificate Signature Algorithm". (For StackOverflow's certificate, its value is "PKCS #1 SHA-1 With RSA Encryption".)

    Uninstall mongoDB from ubuntu

    Sometimes this works;

    sudo apt-get install mongodb-org --fix-missing --fix-broken
    sudo apt-get autoremove mongodb-org --fix-missing --fix-broken
    

    android on Text Change Listener

    You can also use the hasFocus() method:

    public void onTextChanged(CharSequence s, int start,
         int before, int count) {
         if (Field2.hasfocus()){
             Field1.setText("");
         }
       }
    

    Tested this for a college assignment I was working on to convert temperature scales as the user typed them in. Worked perfectly, and it's way simpler.

    String.contains in Java

    Empty is a subset of any string.

    Think of them as what is between every two characters.

    Kind of the way there are an infinite number of points on any sized line...

    (Hmm... I wonder what I would get if I used calculus to concatenate an infinite number of empty strings)

    Note that "".equals("") only though.

    #1071 - Specified key was too long; max key length is 1000 bytes

    As @Devart says, the total length of your index is too long.

    The short answer is that you shouldn't be indexing such long VARCHAR columns anyway, because the index will be very bulky and inefficient.

    The best practice is to use prefix indexes so you're only indexing a left substring of the data. Most of your data will be a lot shorter than 255 characters anyway.

    You can declare a prefix length per column as you define the index. For example:

    ...
    KEY `index` (`parent_menu_id`,`menu_link`(50),`plugin`(50),`alias`(50))
    ...
    

    But what's the best prefix length for a given column? Here's a method to find out:

    SELECT
     ROUND(SUM(LENGTH(`menu_link`)<10)*100/COUNT(`menu_link`),2) AS pct_length_10,
     ROUND(SUM(LENGTH(`menu_link`)<20)*100/COUNT(`menu_link`),2) AS pct_length_20,
     ROUND(SUM(LENGTH(`menu_link`)<50)*100/COUNT(`menu_link`),2) AS pct_length_50,
     ROUND(SUM(LENGTH(`menu_link`)<100)*100/COUNT(`menu_link`),2) AS pct_length_100
    FROM `pds_core_menu_items`;
    

    It tells you the proportion of rows that have no more than a given string length in the menu_link column. You might see output like this:

    +---------------+---------------+---------------+----------------+
    | pct_length_10 | pct_length_20 | pct_length_50 | pct_length_100 |
    +---------------+---------------+---------------+----------------+
    |         21.78 |         80.20 |        100.00 |         100.00 |
    +---------------+---------------+---------------+----------------+
    

    This tells you that 80% of your strings are less than 20 characters, and all of your strings are less than 50 characters. So there's no need to index more than a prefix length of 50, and certainly no need to index the full length of 255 characters.

    PS: The INT(1) and INT(32) data types indicates another misunderstanding about MySQL. The numeric argument has no effect related to storage or the range of values allowed for the column. INT is always 4 bytes, and it always allows values from -2147483648 to 2147483647. The numeric argument is about padding values during display, which has no effect unless you use the ZEROFILL option.

    How do you produce a .d.ts "typings" definition file from an existing JavaScript library?

    As Ryan says, the tsc compiler has a switch --declaration which generates a .d.ts file from a .ts file. Also note that (barring bugs) TypeScript is supposed to be able to compile Javascript, so you can pass existing javascript code to the tsc compiler.

    groovy: safely find a key in a map and return its value

    Groovy maps can be used with the property property, so you can just do:

    def x = mymap.likes
    

    If the key you are looking for (for example 'likes.key') contains a dot itself, then you can use the syntax:

    def x = mymap.'likes.key'
    

    how can I copy a conditional formatting in Excel 2010 to other cells, which is based on a other cells content?

    You can do this in the 'Conditional Formatting' tool in the Home tab of Excel 2010.

    Assuming the existing rule is 'Use a formula to dtermine which cells to format':

    Edit the existing rule, so that the 'Formula' refers to relative rows and columns (i.e. remove $s), and then in the 'Applies to' box, click the icon to make the sheet current and select the cells you want the formatting to apply to (absolute cell references are ok here), then go back to the tool panel and click Apply.

    This will work assuming the relative offsets are appropriate throughout your desired apply-to range.

    You can copy conditional formatting from one cell to another or a range using copy and paste-special with formatting only, assuming you do not mind copying the normal formats.

    Install a Python package into a different directory using pip?

    Newer versions of pip (8 or later) can directly use the --prefix option:

    pip install --prefix=$PREFIX_PATH package_name
    

    where $PREFIX_PATH is the installation prefix where lib, bin and other top-level folders are placed.

    What are good examples of genetic algorithms/genetic programming solutions?

    I don't know if homework counts...

    During my studies we rolled our own program to solve the Traveling Salesman problem.

    The idea was to make a comparison on several criteria (difficulty to map the problem, performance, etc) and we also used other techniques such as Simulated annealing.

    It worked pretty well, but it took us a while to understand how to do the 'reproduction' phase correctly: modeling the problem at hand into something suitable for Genetic programming really struck me as the hardest part...

    It was an interesting course since we also dabbled with neural networks and the like.

    I'd like to know if anyone used this kind of programming in 'production' code.

    How to find the logs on android studio?

    I had the same problem and after some searching I was able to find my logs at the following location:

    C:\Users\<yourid>\.AndroidStudioPreview\system\log

    Instant run in Android Studio 2.0 (how to turn off)

    I had the same exact isuue with the latest Android Studio 2.3.2 and Instant Run.

    here what I did : (I'll give you two ways to achive that one disable for specefic project, and second for whole android studio):

    1. if you want to disable instant-run ONLY for the project that is not compatible (i.e the one with SugarORM lib)

    on root of your projct open gradle-->gradle-wrapper.properties then change the value distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip

    and on your project build.gradle change the value

    classpath 'com.android.tools.build:gradle:2.2.3'
    

    enter image description here

    1. If you want to disable instant-run for all project (Across Android Studio)

    in older version of AS settings for instant run is

    File -> Other Settings -> Default Settings ->Build,Execution,Deployment
    

    However In most recent version of Android Studio i.e 2.3.2 , instant run settings is:

    • for Android Studio Installed on Apple devices -> Preferences... (see following image)
    • for Android Studio Installed on Linux or Windows -> in File-> Settings...

    enter image description here

    enter image description here


    Edited: If for any reason the Instant-run settings is greyed out do this :

    Help-> Find Action... 
    

    enter image description here

    and then type 'enable isntant run' and click (now you should be able to change the value in Preferences... or file->Settings... , if that was the case then this is an Android Studio bug :-)

    enter image description here

    Get commit list between tags in git

    FYI:

    git log tagA...tagB
    

    provides standard log output in a range.

    How do I get which JRadioButton is selected from a ButtonGroup

    You can put and actionCommand to each radio button (string).

    this.jButton1.setActionCommand("dog");
    this.jButton2.setActionCommand("cat");
    this.jButton3.setActionCommand("bird");
    

    Assuming they're already in a ButtonGroup (state_group in this case) you can get the selected radio button like this:

    String selection = this.state_group.getSelection().getActionCommand();
    

    Hope this helps

    HTTP Error 404 when running Tomcat from Eclipse

    It is because there is no default ROOT web application. When you create some web app and deploy it to Tomcat using Eclipse, then you will be able to access it with the URL in the form of

    http://localhost:8080/YourWebAppName
    

    where YourWebAppName is some name you give to your web app (the so called application context path).

    Quote from Jetty Documentation Wiki (emphasis mine):

    The context path is the prefix of a URL path that is used to select the web application to which an incoming request is routed. Typically a URL in a Java servlet server is of the format http://hostname.com/contextPath/servletPath/pathInfo, where each of the path elements may be zero or more / separated elements. If there is no context path, the context is referred to as the root context.


    If you still want the default app which is accessed with the URL of the form

    http://localhost:8080
    

    or if you change the default 8080 port to 80, then just

    http://localhost
    

    i.e. without application context path read the following (quote from Tutorial: Installing Tomcat 7 and Using it with Eclipse, emphasis mine):

    Copy the ROOT (default) Web app into Eclipse. Eclipse forgets to copy the default apps (ROOT, examples, docs, etc.) when it creates a Tomcat folder inside the Eclipse workspace. Go to C:\apache-tomcat-7.0.34\webapps and copy the ROOT folder. Then go to your Eclipse workspace, go to the .metadata folder, and search for "wtpwebapps". You should find something like C:\your-eclipse-workspace-location\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps (or .../tmp1/wtpwebapps if you already had another server registered in Eclipse). Go to the wtpwebapps folder and paste ROOT (say "yes" if asked if you want to merge/replace folders/files). Then reload http://localhost/ to see the Tomcat welcome page.

    Difference between <input type='button' /> and <input type='submit' />

    It should be also mentioned that a named input of type="submit" will be also submitted together with the other form's named fields while a named input type="button" won't.

    With other words, in the example below, the named input name=button1 WON'T get submitted while the named input name=submit1 WILL get submitted.

    Sample HTML form (index.html):

    <form action="checkout.php" method="POST">
    
      <!-- this won't get submitted despite being named -->
      <input type="button" name="button1" value="a button">
    
      <!-- this one does; so the input's TYPE is important! -->
      <input type="submit" name="submit1" value="a submit button">
    
    </form>
    

    The PHP script (checkout.php) that process the above form's action:

    <?php var_dump($_POST); ?>
    

    Test the above on your local machine by creating the two files in a folder named /tmp/test/ then running the built-in PHP web server from shell:

    php -S localhost:3000 -t /tmp/test/
    

    Open your browser at http://localhost:3000 and see for yourself.

    One would wonder why would we need to submit a named button? It depends on the back-end script. For instance the WooCommerce WordPress plugin won't process a Checkout page posted unless the Place Order named button is submitted too. If you alter its type from submit to button then this button won't get submitted and thus the Checkout form would never get processed.

    This is probably a small detail but you know, the devil is in the details.

    HTTP GET with request body

    You can either send a GET with a body or send a POST and give up RESTish religiosity (it's not so bad, 5 years ago there was only one member of that faith -- his comments linked above).

    Neither are great decisions, but sending a GET body may prevent problems for some clients -- and some servers.

    Doing a POST might have obstacles with some RESTish frameworks.

    Julian Reschke suggested above using a non-standard HTTP header like "SEARCH" which could be an elegant solution, except that it's even less likely to be supported.

    It might be most productive to list clients that can and cannot do each of the above.

    Clients that cannot send a GET with body (that I know of):

    • XmlHTTPRequest Fiddler

    Clients that can send a GET with body:

    • most browsers

    Servers & libraries that can retrieve a body from GET:

    • Apache
    • PHP

    Servers (and proxies) that strip a body from GET:

    • ?

    How to get a list of properties with a given attribute?

    var props = t.GetProperties().Where(
                    prop => Attribute.IsDefined(prop, typeof(MyAttribute)));
    

    This avoids having to materialize any attribute instances (i.e. it is cheaper than GetCustomAttribute[s]().

    PHP Multidimensional Array Searching (Find key by specific value)

    I would do like below, where $products is the actual array given in the problem at the very beginning.

    print_r(
      array_search("breville-variable-temperature-kettle-BKE820XL", 
      array_map(function($product){return $product["slug"];},$products))
    );
    

    Convert double to BigDecimal and set BigDecimal Precision

    The reason of such behaviour is that the string that is printed is the exact value - probably not what you expected, but that's the real value stored in memory - it's just a limitation of floating point representation.

    According to javadoc, BigDecimal(double val) constructor behaviour can be unexpected if you don't take into consideration this limitation:

    The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.

    So in your case, instead of using

    double val = 77.48;
    new BigDecimal(val);
    

    use

    BigDecimal.valueOf(val);
    

    Value that is returned by BigDecimal.valueOf is equal to that resulting from invocation of Double.toString(double).

    What does ':' (colon) do in JavaScript?

    You guys are forgetting that the colon is also used in the ternary operator (though I don't know if jquery uses it for this purpose).

    the ternary operator is an expression form (expressions return a value) of an if/then statement. it's used like this:

    var result = (condition) ? (value1) : (value2) ;
    

    A ternary operator could also be used to produce side effects just like if/then, but this is profoundly bad practice.

    Node.js – events js 72 throw er unhandled 'error' event

    For what is worth, I got this error doing a clean install of nodejs and npm packages of my current linux-distribution I've installed meteor using

    npm install metor
    

    And got the above referenced error. After wasting some time, I found out I should have used meteor's way to update itself:

    meteor update
    

    This command output, among others, the message that meteor was severely outdated (over 2 years) and that it was going to install itself using:

    curl https://install.meteor.com/ | sh
    

    Which was probably the command I should have run in the first place.

    So the solution might be to upgrade/update whatever nodejs package(js) you're using.

    Find Number of CPUs and Cores per CPU using Command Prompt

    You can also enter msinfo32 into the command line.

    It will bring up all your system information. Then, in the find box, just enter processor and it will show you your cores and logical processors for each CPU. I found this way to be easiest.

    How can the default node version be set using NVM?

    (nvm maintainer here)

    nvm alias default 6.11.5 if you want it pegged to that specific version.

    You can also do nvm alias default 6.

    Either way, you'll want to upgrade to the latest version of nvm (v0.33.11 as of this writing)

    Understanding the grid classes ( col-sm-# and col-lg-# ) in Bootstrap 3

    This might be late as I think most of us are using BS4. This article explained all the questions you asked in a detailed and simple manner also includes what to do when. The detailed guide to use bs4 or bootstrap

    https://uxplanet.org/how-the-bootstrap-4-grid-works-a1b04703a3b7

    Replace X-axis with own values

    Yo could also set labels = FALSE inside axis(...) and print the labels in a separate command with Text. With this option you can rotate the text the text in case you need it

    lablist<-as.vector(c(1:10))
    axis(1, at=seq(1, 10, by=1), labels = FALSE)
    text(seq(1, 10, by=1), par("usr")[3] - 0.2, labels = lablist, srt = 45, pos = 1, xpd = TRUE)
    

    Detailed explanation here

    Image with rotated labels

    How to parse a text file with C#

    OK, here's what we do: open the file, read it line by line, and split it by tabs. Then we grab the second integer and loop through the rest to find the path.

    StreamReader reader = File.OpenText("filename.txt");
    string line;
    while ((line = reader.ReadLine()) != null) 
    {
        string[] items = line.Split('\t');
        int myInteger = int.Parse(items[1]);   // Here's your integer.
    
        // Now let's find the path.
        string path = null;
        foreach (string item in items) 
        {
            if (item.StartsWith("item\\") && item.EndsWith(".ddj"))
                path = item;
        }
    
        // At this point, `myInteger` and `path` contain the values we want
        // for the current line. We can then store those values or print them,
        // or anything else we like.
    }
    

    Style input type file?

    Use the clip property along with opacity, z-index, absolute positioning, and some browser filters to place the file input over the desired button:

    http://en.wikibooks.org/wiki/Cascading_Style_Sheets/Clipping

    Merging dataframes on index with pandas

    You should be able to use join, which joins on the index as default. Given your desired result, you must use outer as the join type.

    >>> df1.join(df2, how='outer')
                V1  V2
    A 1/1/2012  12  15
      2/1/2012  14 NaN
      3/1/2012 NaN  21
    B 1/1/2012  15  24
      2/1/2012   8   9
    C 1/1/2012  17 NaN
      2/1/2012   9 NaN
    D 1/1/2012 NaN   7
      2/1/2012 NaN  16
    

    Signature: _.join(other, on=None, how='left', lsuffix='', rsuffix='', sort=False) Docstring: Join columns with other DataFrame either on index or on a key column. Efficiently Join multiple DataFrame objects by index at once by passing a list.

    Converting Object to JSON and JSON to Object in PHP, (library like Gson for Java)

    This should do the trick!

    // convert object => json
    $json = json_encode($myObject);
    
    // convert json => object
    $obj = json_decode($json);
    

    Here's an example

    $foo = new StdClass();
    $foo->hello = "world";
    $foo->bar = "baz";
    
    $json = json_encode($foo);
    echo $json;
    //=> {"hello":"world","bar":"baz"}
    
    print_r(json_decode($json));
    // stdClass Object
    // (
    //   [hello] => world
    //   [bar] => baz
    // )
    

    If you want the output as an Array instead of an Object, pass true to json_decode

    print_r(json_decode($json, true));
    // Array
    // (
    //   [hello] => world
    //   [bar] => baz
    // )    
    

    More about json_encode()

    See also: json_decode()

    How to decorate a class?

    I'd agree inheritance is a better fit for the problem posed.

    I found this question really handy though on decorating classes, thanks all.

    Here's another couple of examples, based on other answers, including how inheritance affects things in Python 2.7, (and @wraps, which maintains the original function's docstring, etc.):

    def dec(klass):
        old_foo = klass.foo
        @wraps(klass.foo)
        def decorated_foo(self, *args ,**kwargs):
            print('@decorator pre %s' % msg)
            old_foo(self, *args, **kwargs)
            print('@decorator post %s' % msg)
        klass.foo = decorated_foo
        return klass
    
    @dec  # No parentheses
    class Foo...
    

    Often you want to add parameters to your decorator:

    from functools import wraps
    
    def dec(msg='default'):
        def decorator(klass):
            old_foo = klass.foo
            @wraps(klass.foo)
            def decorated_foo(self, *args ,**kwargs):
                print('@decorator pre %s' % msg)
                old_foo(self, *args, **kwargs)
                print('@decorator post %s' % msg)
            klass.foo = decorated_foo
            return klass
        return decorator
    
    @dec('foo decorator')  # You must add parentheses now, even if they're empty
    class Foo(object):
        def foo(self, *args, **kwargs):
            print('foo.foo()')
    
    @dec('subfoo decorator')
    class SubFoo(Foo):
        def foo(self, *args, **kwargs):
            print('subfoo.foo() pre')
            super(SubFoo, self).foo(*args, **kwargs)
            print('subfoo.foo() post')
    
    @dec('subsubfoo decorator')
    class SubSubFoo(SubFoo):
        def foo(self, *args, **kwargs):
            print('subsubfoo.foo() pre')
            super(SubSubFoo, self).foo(*args, **kwargs)
            print('subsubfoo.foo() post')
    
    SubSubFoo().foo()
    

    Outputs:

    @decorator pre subsubfoo decorator
    subsubfoo.foo() pre
    @decorator pre subfoo decorator
    subfoo.foo() pre
    @decorator pre foo decorator
    foo.foo()
    @decorator post foo decorator
    subfoo.foo() post
    @decorator post subfoo decorator
    subsubfoo.foo() post
    @decorator post subsubfoo decorator
    

    I've used a function decorator, as I find them more concise. Here's a class to decorate a class:

    class Dec(object):
    
        def __init__(self, msg):
            self.msg = msg
    
        def __call__(self, klass):
            old_foo = klass.foo
            msg = self.msg
            def decorated_foo(self, *args, **kwargs):
                print('@decorator pre %s' % msg)
                old_foo(self, *args, **kwargs)
                print('@decorator post %s' % msg)
            klass.foo = decorated_foo
            return klass
    

    A more robust version that checks for those parentheses, and works if the methods don't exist on the decorated class:

    from inspect import isclass
    
    def decorate_if(condition, decorator):
        return decorator if condition else lambda x: x
    
    def dec(msg):
        # Only use if your decorator's first parameter is never a class
        assert not isclass(msg)
    
        def decorator(klass):
            old_foo = getattr(klass, 'foo', None)
    
            @decorate_if(old_foo, wraps(klass.foo))
            def decorated_foo(self, *args ,**kwargs):
                print('@decorator pre %s' % msg)
                if callable(old_foo):
                    old_foo(self, *args, **kwargs)
                print('@decorator post %s' % msg)
    
            klass.foo = decorated_foo
            return klass
    
        return decorator
    

    The assert checks that the decorator has not been used without parentheses. If it has, then the class being decorated is passed to the msg parameter of the decorator, which raises an AssertionError.

    @decorate_if only applies the decorator if condition evaluates to True.

    The getattr, callable test, and @decorate_if are used so that the decorator doesn't break if the foo() method doesn't exist on the class being decorated.

    An existing connection was forcibly closed by the remote host - WCF

    I had this issue because my website did not have a certificate bound to the SSL port. I thought I'd mention it because I didn't find this answer anywhere in the googleweb and it took me hours to figure it out. Nothing showed up in the event viewer, which was totally awesome for diagnosing it. Hope this saves someone else the pain.

    Put content in HttpResponseMessage object?

    You can create your own specialised content types. For example one for Json content and one for Xml content (then just assign them to the HttpResponseMessage.Content):

    public class JsonContent : StringContent
    {
        public JsonContent(string content)
            : this(content, Encoding.UTF8)
        {
        }
    
        public JsonContent(string content, Encoding encoding)
            : base(content, encoding, "application/json")
        {
        }
    }
    
    public class XmlContent : StringContent
    {
        public XmlContent(string content) 
            : this(content, Encoding.UTF8)
        {
        }
    
        public XmlContent(string content, Encoding encoding)
            : base(content, encoding, "application/xml")
        {
        }
    }
    

    Convert textbox text to integer

    Example:

    int x = Convert.ToInt32(this.txtboxname.Text) + 1 //You dont need the "this"
    txtboxname.Text = x.ToString();
    

    The x.ToString() makes the integer into string to show that in the text box.

    Result:

    1. You put number in the text box.
    2. You click on the button or something running the function.
    3. You see your number just bigger than your number by one in your text box.

    :)

    how to use javascript Object.defineProperty

    Summary:

    Object.defineProperty(player, "health", {
        get: function () {
            return 10 + ( player.level * 15 );
        }
    });
    

    Object.defineProperty is used in order to make a new property on the player object. Object.defineProperty is a function which is natively present in the JS runtime environemnt and takes the following arguments:

    Object.defineProperty(obj, prop, descriptor)

    1. The object on which we want to define a new property
    2. The name of the new property we want to define
    3. descriptor object

    The descriptor object is the interesting part. In here we can define the following things:

    1. configurable <boolean>: If true the property descriptor may be changed and the property may be deleted from the object. If configurable is false the descriptor properties which are passed in Object.defineProperty cannot be changed.
    2. Writable <boolean>: If true the property may be overwritten using the assignment operator.
    3. Enumerable <boolean>: If true the property can be iterated over in a for...in loop. Also when using the Object.keys function the key will be present. If the property is false they will not be iterated over using a for..in loop and not show up when using Object.keys.
    4. get <function> : A function which is called whenever is the property is required. Instead of giving the direct value this function is called and the returned value is given as the value of the property
    5. set <function> : A function which is called whenever is the property is assigned. Instead of setting the direct value this function is called and the returned value is used to set the value of the property.

    Example:

    _x000D_
    _x000D_
    const player = {_x000D_
      level: 10_x000D_
    };_x000D_
    _x000D_
    Object.defineProperty(player, "health", {_x000D_
      configurable: true,_x000D_
      enumerable: false,_x000D_
      get: function() {_x000D_
        console.log('Inside the get function');_x000D_
        return 10 + (player.level * 15);_x000D_
      }_x000D_
    });_x000D_
    _x000D_
    console.log(player.health);_x000D_
    // the get function is called and the return value is returned as a value_x000D_
    _x000D_
    for (let prop in player) {_x000D_
      console.log(prop);_x000D_
      // only prop is logged here, health is not logged because is not an iterable property._x000D_
      // This is because we set the enumerable to false when defining the property_x000D_
    }
    _x000D_
    _x000D_
    _x000D_

    How to use cURL in Java?

    Use Runtime to call Curl. This code works for both Ubuntu and Windows.

    String[] commands = new String {"curl", "-X", "GET", "http://checkip.amazonaws.com"};
    Process process = Runtime.getRuntime().exec(commands);
    BufferedReader reader = new BufferedReader(new 
    InputStreamReader(process.getInputStream()));
    String line;
    String response;
    while ((line = reader.readLine()) != null) {
        response.append(line);
    }
    

    .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible

    For me, I had ~6 different Nuget packages to update and when I selected Microsoft.AspNetCore.All first, I got the referenced error.

    I started at the bottom and updated others first (EF Core, EF Design Tools, etc), then when the only one that was left was Microsoft.AspNetCore.All it worked fine.

    "document.getElementByClass is not a function"

    document.querySelectorAll works pretty well and allows you to further narrow down your selection.

    https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

    How do I put an image into my picturebox using ImageLocation?

    if you provide a bad path or a broken link, if the compiler cannot find the image, the picture box would display an X icon on its body.

    PictureBox picture = new PictureBox
            {
                Name = "pictureBox",
                Size = new Size(100, 50),
                Location = new Point(14, 17),
                Image = Image.FromFile(@"c:\Images\test.jpg"),
                SizeMode = PictureBoxSizeMode.CenterImage
            };
    p.Controls.Add(picture);
    

    OR

    PictureBox picture = new PictureBox
            {
                Name = "pictureBox",
                Size = new Size(100, 50),
                Location = new Point(14, 17),
                ImageLocation = @"c:\Images\test.jpg",
                SizeMode = PictureBoxSizeMode.CenterImage
            };
    p.Controls.Add(picture);
    

    i'm not sure where you put images in your folder structure but you can find the path as bellow

     picture.ImageLocation = Path.Combine(System.Windows.Forms.Application.StartupPath, "Resources\Images\1.jpg");
    

    How to display line numbers in 'less' (GNU)

    You can also press = while less is open to just display (at the bottom of the screen) information about the current screen, including line numbers, with format:

    myfile.txt lines 20530-20585/1816468 byte 1098945/116097872 1%  (press RETURN)
    

    So here for example, the screen was currently showing lines 20530-20585, and the files has a total of 1816468 lines.

    Global variables in c#.net

    I second jdk's answer: any public static member of any class of your application can be considered as a "global variable".

    However, do note that this is an ASP.NET application, and as such, it's a multi-threaded context for your global variables. Therefore, you should use some locking mechanism when you update and/or read the data to/from these variables. Otherwise, you might get your data in a corrupted state.

    Error - is not marked as serializable

    You need to add a Serializable attribute to the class which you want to serialize.

    [Serializable]
    public class OrgPermission
    

    <div> cannot appear as a descendant of <p>

    I got this warning by using Material UI components, then I test the component="div" as prop to the below code and everything became correct:

    import Grid from '@material-ui/core/Grid';
    import Typography from '@material-ui/core/Typography';
    
    <Typography component="span">
      <Grid component="span">
        Lorem Ipsum
      </Grid>
    </Typography>
    

    Actually, this warning happens because in the Material UI the default HTML tag of Grid component is div tag and the default Typography HTML tag is p tag, So now the warning happens,

    Warning: validateDOMnesting(...): <div> cannot appear as a descendant of <p>
    

    SFTP in Python? (platform independent)

    With RSA Key then refer here

    Snippet:

    import pysftp
    import paramiko
    from base64 import decodebytes
    
    keydata = b"""AAAAB3NzaC1yc2EAAAADAQABAAABAQDl""" 
    key = paramiko.RSAKey(data=decodebytes(keydata)) 
    cnopts = pysftp.CnOpts()
    cnopts.hostkeys.add(host, 'ssh-rsa', key)
    
    
    with pysftp.Connection(host=host, username=username, password=password, cnopts=cnopts) as sftp:   
      with sftp.cd(directory):
        sftp.put(file_to_sent_to_ftp)
    

    C# Linq Where Date Between 2 Dates

    I had a problem getting this to work.

    I had two dates in a db line and I need to add them to a list for yesterday, today and tomorrow.

    this is my solution:

            var yesterday = DateTime.Today.AddDays(-1);
            var today = DateTime.Today;
            var tomorrow = DateTime.Today.AddDays(1);            
            var vm = new Model()
            {
                Yesterday = _context.Table.Where(x => x.From <= yesterday && x.To >= yesterday).ToList(),
                Today = _context.Table.Where(x => x.From <= today & x.To >= today).ToList(),
                Tomorrow = _context.Table.Where(x => x.From <= tomorrow & x.To >= tomorrow).ToList()
            };
    

    Twitter bootstrap scrollable modal

    In case of using .modal {overflow-y: auto;}, would create additional scroll bar on the right of the page, when body is already overflowed.

    The work around for this is to remove overflow from the body tag temporarily and set modal overflow-y to auto.

    Example:

    $('.myModalSelector').on('show.bs.modal', function () {
    
            // Store initial body overflow value
            _initial_body_overflow = $('body').css('overflow');
    
            // Let modal be scrollable
            $(this).css('overflow-y', 'auto');
            $('body').css('overflow', 'hidden');
    
    
        }).on('hide.bs.modal', function () {
    
            // Reverse previous initialization
            $(this).css('overflow-y', 'hidden');
            $('body').css('overflow', _initial_body_overflow);
    });
    

    Jenkins Slave port number for firewall

    I have a similar scenario, and had no problem connecting after setting the JNLP port as you describe, and adding a single firewall rule allowing a connection on the server using that port. Granted it is a randomly selected client port going to a known server port (a host:ANY -> server:1 rule is needed).

    From my reading of the source code, I don't see a way to set the local port to use when making the request from the slave. It's unfortunate, it would be a nice feature to have.

    Alternatives:

    Use a simple proxy on your client that listens on port N and then does forward all data to the actual Jenkins server on the remote host using a constant local port. Connect your slave to this local proxy instead of the real Jenkins server.

    Create a custom Jenkins slave build that allows an option to specify the local port to use.

    Remember also if you are using HTTPS via a self-signed certificate, you must alter the configuration jenkins-slave.xml file on the slave to specify the -noCertificateCheck option on the command line.

    INNER JOIN vs LEFT JOIN performance in SQL Server

    Your performance problems are more likely to be because of the number of joins you are doing and whether the columns you are joining on have indexes or not.

    Worst case you could easily be doing 9 whole table scans for each join.

    UITableView - scroll to the top

    DONT USE

     tableView.setContentOffset(.zero, animated: true)
    

    It can sometimes set the offset improperly. For example, in my case, the cell was actually slightly above the view with safe area insets. Not good.

    INSTEAD USE

     tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
    

    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

    Using local makefile for CLion instead of CMake

    Newest version has better support literally for any generated Makefiles, through the compiledb

    Three steps:

    1. install compiledb

      pip install compiledb
      
    2. run a dry make

      compiledb -n make 
      

      (do the autogen, configure if needed)

    3. there will be a compile_commands.json file generated open the project and you will see CLion will load info from the json file. If you your CLion still try to find CMakeLists.txt and cannot read compile_commands.json, try to remove the entire folder, re-download the source files, and redo step 1,2,3

    Orignal post: Working with Makefiles in CLion using Compilation DB

    How do you get the length of a list in the JSF expression language?

    You mean size() don't you?

    #{MyBean.somelist.size()}
    

    works for me (using JBoss Seam which has the Jboss EL extensions)

    How to pass html string to webview on android

    I was using some buttons with some events, converted image file coming from server. Loading normal data wasn't working for me, converting into Base64 working just fine.

    String unencodedHtml ="<html><body>'%28' is the code for '('</body></html>";
    tring encodedHtml = Base64.encodeToString(unencodedHtml.getBytes(), Base64.NO_PADDING);
    webView.loadData(encodedHtml, "text/html", "base64");
    

    Find details on WebView

    How can I detect if a selector returns null?

    My favourite is to extend jQuery with this tiny convenience:

    $.fn.exists = function () {
        return this.length !== 0;
    }
    

    Used like:

    $("#notAnElement").exists();
    

    More explicit than using length.

    Algorithm for solving Sudoku

    Hi I've blogged about writing a sudoku solver from scratch in Python and currently writing a whole series about writing a constraint programming solver in Julia (another high level but faster language) You can read the sudoku problem from a file which seems to be easier more handy than a gui or cli way. The general idea it uses is constraint programming. I use the all different / unique constraint but I coded it myself instead of using a constraint programming solver.

    If someone is interested:

    How do I change the number of open files limit in Linux?

    If some of your services are balking into ulimits, it's sometimes easier to put appropriate commands into service's init-script. For example, when Apache is reporting

    [alert] (11)Resource temporarily unavailable: apr_thread_create: unable to create worker thread

    Try to put ulimit -s unlimited into /etc/init.d/httpd. This does not require a server reboot.

    position: fixed doesn't work on iPad and iPhone

    Had the same issue on Iphone X. To fixed it I just add height to the container

    top: 0;
    height: 200px;
    position: fixed;
    

    I just added top:0 because i need my div to stay at top

    write() versus writelines() and concatenated strings

    Why am I unable to use a string for a newline in write() but I can use it in writelines()?

    The idea is the following: if you want to write a single string you can do this with write(). If you have a sequence of strings you can write them all using writelines().

    write(arg) expects a string as argument and writes it to the file. If you provide a list of strings, it will raise an exception (by the way, show errors to us!).

    writelines(arg) expects an iterable as argument (an iterable object can be a tuple, a list, a string, or an iterator in the most general sense). Each item contained in the iterator is expected to be a string. A tuple of strings is what you provided, so things worked.

    The nature of the string(s) does not matter to both of the functions, i.e. they just write to the file whatever you provide them. The interesting part is that writelines() does not add newline characters on its own, so the method name can actually be quite confusing. It actually behaves like an imaginary method called write_all_of_these_strings(sequence).

    What follows is an idiomatic way in Python to write a list of strings to a file while keeping each string in its own line:

    lines = ['line1', 'line2']
    with open('filename.txt', 'w') as f:
        f.write('\n'.join(lines))
    

    This takes care of closing the file for you. The construct '\n'.join(lines) concatenates (connects) the strings in the list lines and uses the character '\n' as glue. It is more efficient than using the + operator.

    Starting from the same lines sequence, ending up with the same output, but using writelines():

    lines = ['line1', 'line2']
    with open('filename.txt', 'w') as f:
        f.writelines("%s\n" % l for l in lines)
    

    This makes use of a generator expression and dynamically creates newline-terminated strings. writelines() iterates over this sequence of strings and writes every item.

    Edit: Another point you should be aware of:

    write() and readlines() existed before writelines() was introduced. writelines() was introduced later as a counterpart of readlines(), so that one could easily write the file content that was just read via readlines():

    outfile.writelines(infile.readlines())
    

    Really, this is the main reason why writelines has such a confusing name. Also, today, we do not really want to use this method anymore. readlines() reads the entire file to the memory of your machine before writelines() starts to write the data. First of all, this may waste time. Why not start writing parts of data while reading other parts? But, most importantly, this approach can be very memory consuming. In an extreme scenario, where the input file is larger than the memory of your machine, this approach won't even work. The solution to this problem is to use iterators only. A working example:

    with open('inputfile') as infile:
        with open('outputfile') as outfile:
            for line in infile:
                outfile.write(line)
    

    This reads the input file line by line. As soon as one line is read, this line is written to the output file. Schematically spoken, there always is only one single line in memory (compared to the entire file content being in memory in case of the readlines/writelines approach).

    Compilation fails with "relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object"

    Simply cleaning the project solved it for me.

    My project is a C++ application (not a shared library). I randomly got this error after a lot of successful builds.

    jQuery: get data attribute

    Change IDs and data attributes as you wish!

      <select id="selectVehicle">
           <option value="1" data-year="2011">Mazda</option>
           <option value="2" data-year="2015">Honda</option>
           <option value="3" data-year="2008">Mercedes</option>
           <option value="4" data-year="2005">Toyota</option>
      </select>
    
    $("#selectVehicle").change(function () {
         alert($(this).find(':selected').data("year"));
    });
    

    Here is the working example: https://jsfiddle.net/ed5axgvk/1/

    How to make an app's background image repeat

    Ok, here's what I've got in my app. It includes a hack to prevent ListViews from going black while scrolling.

    drawable/app_background.xml:

    <?xml version="1.0" encoding="utf-8"?>
        <bitmap xmlns:android="http://schemas.android.com/apk/res/android"
            android:src="@drawable/actual_pattern_image"
            android:tileMode="repeat" />
    

    values/styles.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    
      <style name="app_theme" parent="android:Theme">
        <item name="android:windowBackground">@drawable/app_background</item>
        <item name="android:listViewStyle">@style/TransparentListView</item>
        <item name="android:expandableListViewStyle">@style/TransparentExpandableListView</item>
      </style>
    
      <style name="TransparentListView" parent="@android:style/Widget.ListView">
        <item name="android:cacheColorHint">@android:color/transparent</item>
      </style>
    
      <style name="TransparentExpandableListView" parent="@android:style/Widget.ExpandableListView">
        <item name="android:cacheColorHint">@android:color/transparent</item>
      </style>
    
    </resources>
    

    AndroidManifest.xml:

    //
    <application android:theme="@style/app_theme">
    //
    

    Quickest way to convert XML to JSON in Java

    I found this the quick and easy way: Used: org.json.XML class from java-json.jar

    if (statusCode == 200 && inputStream != null) {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        StringBuilder responseStrBuilder = new StringBuilder();
    
        String inputStr;
        while ((inputStr = bufferedReader.readLine()) != null) {
            responseStrBuilder.append(inputStr);
        }
    
        jsonObject = XML.toJSONObject(responseStrBuilder.toString());
    }
    

    Using a remote repository with non-standard port

    SSH based git access method can be specified in <repo_path>/.git/config using either a full URL or an SCP-like syntax, as specified in http://git-scm.com/docs/git-clone:

    URL style:

    url = ssh://[user@]host.xz[:port]/path/to/repo.git/
    

    SCP style:

    url = [user@]host.xz:path/to/repo.git/
    

    Notice that the SCP style does not allow a direct port change, relying instead on an ssh_config host definition in your ~/.ssh/config such as:

    Host my_git_host
    HostName git.some.host.org
    Port 24589
    User not_a_root_user
    

    Then you can test in a shell with:

    ssh my_git_host
    

    and alter your SCP-style URI in <repo_path>/.git/config as:

    url = my_git_host:path/to/repo.git/
    

    Oracle DB : java.sql.SQLException: Closed Connection

    It means the connection was successfully established at some point, but when you tried to commit right there, the connection was no longer open. The parameters you mentioned sound like connection pool settings. If so, they're unrelated to this problem. The most likely cause is a firewall between you and the database that is killing connections after a certain amount of idle time. The most common fix is to make your connection pool run a validation query when a connection is checked out from it. This will immediately identify and evict dead connnections, ensuring that you only get good connections out of the pool.

    Convert Bitmap to File

    Hope this helps u

    class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    
        // Get the bitmap from assets and display into image view
        val bitmap = assetsToBitmap("tulip.jpg")
        // If bitmap is not null
        bitmap?.let {
            image_view_bitmap.setImageBitmap(bitmap)
        }
    
    
        // Click listener for button widget
        button.setOnClickListener{
            if(bitmap!=null){
                // Save the bitmap to a file and display it into image view
                val uri = bitmapToFile(bitmap)
                image_view_file.setImageURI(uri)
    
                // Display the saved bitmap's uri in text view
                text_view.text = uri.toString()
    
                // Show a toast message
                toast("Bitmap saved in a file.")
            }else{
                toast("bitmap not found.")
            }
        }
    }
    
    
    // Method to get a bitmap from assets
    private fun assetsToBitmap(fileName:String):Bitmap?{
        return try{
            val stream = assets.open(fileName)
            BitmapFactory.decodeStream(stream)
        }catch (e:IOException){
            e.printStackTrace()
            null
        }
    }
    
    
    // Method to save an bitmap to a file
    private fun bitmapToFile(bitmap:Bitmap): Uri {
        // Get the context wrapper
        val wrapper = ContextWrapper(applicationContext)
    
        // Initialize a new file instance to save bitmap object
        var file = wrapper.getDir("Images",Context.MODE_PRIVATE)
        file = File(file,"${UUID.randomUUID()}.jpg")
    
        try{
            // Compress the bitmap and save in jpg format
            val stream:OutputStream = FileOutputStream(file)
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream)
            stream.flush()
            stream.close()
        }catch (e:IOException){
            e.printStackTrace()
        }
    
        // Return the saved bitmap uri
        return Uri.parse(file.absolutePath)
    }
    

    }

    Turn Pandas Multi-Index into column

    The reset_index() is a pandas DataFrame method that will transfer index values into the DataFrame as columns. The default setting for the parameter is drop=False (which will keep the index values as columns).

    All you have to do add .reset_index(inplace=True) after the name of the DataFrame:

    df.reset_index(inplace=True)  
    

    Element implicitly has an 'any' type because expression of type 'string' can't be used to index

    I have made a simulation of the problem. looks like the issue is how we should Access Object Properties Dynamically Using Bracket Notation in Typescript

    interface IUserProps {
      name: string;
      age: number;
    }
    
    export default class User {
      constructor(private data: IUserProps) {}
    
      get(propName: string): string | number {
        return this.data[propName as keyof IUserProps];
      }
    }
    
    

    I found a blog that might be helpful to understand this better.

    here is a link https://www.nadershamma.dev/blog/2019/how-to-access-object-properties-dynamically-using-bracket-notation-in-typescript/

    Regular expression for decimal number

    In general, i.e. unlimited decimal places:

    ^-?(([1-9]\d*)|0)(.0*[1-9](0*[1-9])*)?$

    Is it safe to store a JWT in localStorage with ReactJS?

    A way to look at this is to consider the level of risk or harm.

    Are you building an app with no users, POC/MVP? Are you a startup who needs to get to market and test your app quickly? If yes, I would probably just implement the simplest solution and maintain focus on finding product-market-fit. Use localStorage as its often easier to implement.

    Are you building a v2 of an app with many daily active users or an app that people/businesses are heavily dependent on. Would getting hacked mean little or no room for recovery? If so, I would take a long hard look at your dependencies and consider storing token information in an http-only cookie.

    Using both localStorage and cookie/session storage have their own pros and cons.

    As stated by first answer: If your application has an XSS vulnerability, neither will protect your user. Since most modern applications have a dozen or more different dependencies, it becomes increasingly difficult to guarantee that one of your application's dependencies is not XSS vulnerable.

    If your application does have an XSS vulnerability and a hacker has been able to exploit it, the hacker will be able to perform actions on behalf of your user. The hacker can perform GET/POST requests by retrieving token from localStorage or can perform POST requests if token is stored in a http-only cookie.

    The only down-side of the storing your token in local storage is the hacker will be able to read your token.

    What bitrate is used for each of the youtube video qualities (360p - 1080p), in regards to flowplayer?

    Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:

                       240p       360p        480p        720p        1080p
    Resolution      426 x 240   640 x 360   854x480     1280x720    1920x1080
    Video Bitrates                   
    Maximum         700 Kbps    1000 Kbps   2000 Kbps   4000 Kbps   6000 Kbps
    Recommended     400 Kbps    750 Kbps    1000 Kbps   2500 Kbps   4500 Kbps
    Minimum         300 Kbps    400 Kbps    500 Kbps    1500 Kbps   3000 Kbps
    

    It would appear as though this is the case, although the numbers dont sync up to the google table above:

    // the bitrates, video width and file names for this clip
          bitrates: [
            { url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
            { url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
            { url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
          ],