Programs & Examples On #Jsfl

.jsfl files are used to add functionality in the Flash Authoring environment; they contain JavaScript code and access the Flash JavaScript API.

How to query DATETIME field using only date in Microsoft SQL Server?

use this

select * from TableName where DateTimeField > date() and  DateTimeField < date() + 1

Count the number of occurrences of each letter in string

Let's assume you have a system where char is eight bit and all the characters you're trying to count are encoded using a non-negative number. In this case, you can write:

const char *str = "The quick brown fox jumped over the lazy dog.";

int counts[256] = { 0 };

int i;
size_t len = strlen(str);

for (i = 0; i < len; i++) {
    counts[(int)(str[i])]++;
}

for (i = 0; i < 256; i++) {
    if ( count[i] != 0) {
        printf("The %c. character has %d occurrences.\n", i, counts[i]);
    }
}

Note that this will count all the characters in the string. If you are 100% absolutely positively sure that your string will have only letters (no numbers, no whitespace, no punctuation) inside, then 1. asking for "case insensitiveness" starts to make sense, 2. you can reduce the number of entries to the number of characters in the English alphabet (namely 26) and you can write something like this:

#include <ctype.h>
#include <string.h>
#include <stdlib.h>

const char *str = "TheQuickBrownFoxJumpedOverTheLazyDog";

int counts[26] = { 0 };

int i;
size_t len = strlen(str);

for (i = 0; i < len; i++) {
    // Just in order that we don't shout ourselves in the foot
    char c = str[i];
    if (!isalpha(c)) continue;

    counts[(int)(tolower(c) - 'a')]++;
}

for (i = 0; i < 26; i++) {
    printf("'%c' has %2d occurrences.\n", i + 'a', counts[i]);
}

Get hours difference between two dates in Moment Js

In my case, I wanted hours and minutes:

var duration = moment.duration(end.diff(startTime));
var hours = duration.hours(); //hours instead of asHours
var minutes = duration.minutes(); //minutes instead of asMinutes

For more info refer to the official docs.

Want to download a Git repository, what do I need (windows machine)?

Install mysysgit. (Same as Greg Hewgill's answer.)

Install Tortoisegit. (Tortoisegit requires mysysgit or something similiar like Cygwin.)

After TortoiseGit is installed, right-click on a folder, select Git Clone..., then enter the Url of the repository, then click Ok.

This answer is not any better than just installing mysysgit, but you can avoid the dreaded command line. :)

How do I get the last four characters from a string in C#?

Suggest using TakeLast method, for example: new String(text.TakeLast(4).ToArray())

When does a cookie with expiration time 'At end of session' expire?

Just to correct mingos' answer:

If you set the expiration time to 0, the cookie won't be created at all. I've tested this on Google Chrome at least, and when set to 0 that was the result. The cookie, I guess, expires immediately after creation.

To set a cookie so it expires at the end of the browsing session, simply OMIT the expiration parameter altogether.

Example:

Instead of:

document.cookie = "cookie_name=cookie_value; 0; path=/";

Just write:

document.cookie = "cookie_name=cookie_value; path=/";

Errno 10061 : No connection could be made because the target machine actively refused it ( client - server )

The below changes fixed my problem. I struggled with the same error for a week. I would like to share with you all that the solution is simply host = '' in the server and the client host = ip of the server.  

How to set Grid row and column positions programmatically

for (int i = 0; i < 6; i++)
{
    test.ColumnDefinitions.Add(new ColumnDefinition());

    Label t1 = new Label();
    t1.Content = "Test" + i;

    Grid.SetColumn(t1, i);
    Grid.SetRow(t1, 0);
    test.Children.Add(t1);
}

How to make Excel VBA variables available to multiple macros?

Declare them outside the subroutines, like this:

Public wbA as Workbook
Public wbB as Workbook
Sub MySubRoutine()
    Set wbA = Workbooks.Open("C:\file.xlsx")
    Set wbB = Workbooks.Open("C:\file2.xlsx")
    OtherSubRoutine
End Sub
Sub OtherSubRoutine()
    MsgBox wbA.Name, vbInformation
End Sub

Alternately, you can pass variables between subroutines:

Sub MySubRoutine()
Dim wbA as Workbook
Dim wbB as Workbook
    Set wbA = Workbooks.Open("C:\file.xlsx")
    Set wbB = Workbooks.Open("C:\file2.xlsx")
    OtherSubRoutine wbA, wbB
End Sub
Sub OtherSubRoutine(wb1 as Workbook, wb2 as Workbook)
    MsgBox wb1.Name, vbInformation
    MsgBox wb2.Name, vbInformation
End Sub

Or use Functions to return values:

Sub MySubroutine()
    Dim i as Long
    i = MyFunction()
    MsgBox i
End Sub
Function MyFunction()
    'Lots of code that does something
    Dim x As Integer, y as Double
    For x = 1 to 1000
        'Lots of code that does something
    Next
    MyFunction = y
End Function

In the second method, within the scope of OtherSubRoutine you refer to them by their parameter names wb1 and wb2. Passed variables do not need to use the same names, just the same variable types. This allows you some freedom, for example you have a loop over several workbooks, and you can send each workbook to a subroutine to perform some action on that Workbook, without making all (or any) of the variables public in scope.

A Note About User Forms

Personally I would recommend keeping Option Explicit in all of your modules and forms (this prevents you from instantiating variables with typos in their names, like lCoutn when you meant lCount etc., among other reasons).

If you're using Option Explicit (which you should), then you should qualify module-scoped variables for style and to avoid ambiguity, and you must qualify user-form Public scoped variables, as these are not "public" in the same sense. For instance, i is undefined, though it's Public in the scope of UserForm1:

enter image description here

You can refer to it as UserForm1.i to avoid the compile error, or since forms are New-able, you can create a variable object to contain reference to your form, and refer to it that way:

enter image description here

NB: In the above screenshots x is declared Public x as Long in another standard code module, and will not raise the compilation error. It may be preferable to refer to this as Module2.x to avoid ambiguity and possible shadowing in case you re-use variable names...

sqlplus error on select from external table: ORA-29913: error in executing ODCIEXTTABLEOPEN callout

When you want to create an external_table, all field's name must be written in UPPERCASE.

Done.

Object Required Error in excel VBA

The Set statement is only used for object variables (like Range, Cell or Worksheet in Excel), while the simple equal sign '=' is used for elementary datatypes like Integer. You can find a good explanation for when to use set here.

The other problem is, that your variable g1val isn't actually declared as Integer, but has the type Variant. This is because the Dim statement doesn't work the way you would expect it, here (see example below). The variable has to be followed by its type right away, otherwise its type will default to Variant. You can only shorten your Dim statement this way:

Dim intColumn As Integer, intRow As Integer  'This creates two integers

For this reason, you will see the "Empty" instead of the expected "0" in the Watches window.

Try this example to understand the difference:

Sub Dimming()

  Dim thisBecomesVariant, thisIsAnInteger As Integer
  Dim integerOne As Integer, integerTwo As Integer

  MsgBox TypeName(thisBecomesVariant)  'Will display "Empty"
  MsgBox TypeName(thisIsAnInteger )  'Will display "Integer"
  MsgBox TypeName(integerOne )  'Will display "Integer"
  MsgBox TypeName(integerTwo )  'Will display "Integer"

  'By assigning an Integer value to a Variant it becomes Integer, too
  thisBecomesVariant = 0
  MsgBox TypeName(thisBecomesVariant)  'Will display "Integer"

End Sub

Two further notices on your code:

First remark: Instead of writing

'If g1val is bigger than the value in the current cell
If g1val > Cells(33, i).Value Then
  g1val = g1val   'Don't change g1val
Else
  g1val = Cells(33, i).Value  'Otherwise set g1val to the cell's value
End If

you could simply write

'If g1val is smaller or equal than the value in the current cell
If g1val <= Cells(33, i).Value Then
  g1val = Cells(33, i).Value  'Set g1val to the cell's value 
End If

Since you don't want to change g1val in the other case.

Second remark: I encourage you to use Option Explicit when programming, to prevent typos in your program. You will then have to declare all variables and the compiler will give you a warning if a variable is unknown.

How do I schedule jobs in Jenkins?

Jenkins lets you set up multiple times, separated by line breaks.

If you need it to build daily at 7 am, along with every Sunday at 4 pm, the below works well.

H 7 * * *

H 16 * * 0

How can I switch to a tag/branch in hg?

Once you have cloned the repo, you have everything: you can then hg up branchname or hg up tagname to update your working copy.

UP: hg up is a shortcut of hg update, which also has hg checkout alias for people with git habits.

How to use OKHTTP to make a post request?

You should check tutorials on lynda.com. Here is an example of how to encode the parameters, make HTTP request and then parse response to json object.

public JSONObject getJSONFromUrl(String str_url, List<NameValuePair> params) {      
        String reply_str = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(str_url);
            OkHttpClient client = new OkHttpClient();
            HttpURLConnection con = client.open(url);                           
            con.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
            writer.write(getEncodedParams(params));
            writer.flush();     
            StringBuilder sb = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));           
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }           
            reply_str = sb.toString();              
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }

        // try parse the string to a JSON object. There are better ways to parse data.
        try {
            jObj = new JSONObject(reply_str);            
        } catch (JSONException e) {   
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }     
      return jObj;
    }

    //in this case it's NameValuePair, but you can use any container
    public String getEncodedParams(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();
        for (NameValuePair nvp : params) {
            String key = nvp.getName();
            String param_value = nvp.getValue();
            String value = null;
            try {
                value = URLEncoder.encode(param_value, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            if (sb.length() > 0) {
                sb.append("&");
            }
            sb.append(key + "=" + value);
        }
        return sb.toString();
    }

How to hide app title in android?

You can do it programatically:

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;

public class ActivityName extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // remove title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);
    }
}

Or you can do it via your AndroidManifest.xml file:

<activity android:name=".ActivityName"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen">
</activity>

Edit: I added some lines so that you can show it in fullscreen, as it seems that's what you want.

Auto-fit TextView for Android

Since Android O, it's possible to auto resize text in xml:

https://developer.android.com/preview/features/autosizing-textview.html

  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:autoSizeTextType="uniform"
    app:autoSizeMinTextSize="12sp"
    app:autoSizeMaxTextSize="100sp"
    app:autoSizeStepGranularity="2sp"
  />

Android O allows you to instruct a TextView to let the text size expand or contract automatically to fill its layout based on the TextView's characteristics and boundaries. This setting makes it easier to optimize the text size on different screens with dynamic content.

The Support Library 26.0 Beta provides full support to the autosizing TextView feature on devices running Android versions prior to Android O. The library provides support to Android 4.0 (API level 14) and higher. The android.support.v4.widget package contains the TextViewCompat class to access features in a backward-compatible fashion.

How do I detect a click outside an element?

$('#propertyType').on("click",function(e){
          self.propertyTypeDialog = !self.propertyTypeDialog;
          b = true;
          e.stopPropagation();
          console.log("input clicked");
      });

      $(document).on('click','body:not(#propertyType)',function (e) {
          e.stopPropagation();
          if(b == true)  {
              if ($(e.target).closest("#configuration").length == 0) {
                  b = false;
                  self.propertyTypeDialog = false;
                  console.log("outside clicked");
              }
          }
        // console.log($(e.target).closest("#configuration").length);
      });

Variable number of arguments in C++?

It is possible now...using boost any and templates In this case, arguments type can be mixed

#include <boost/any.hpp>
#include <iostream>

#include <vector>
using boost::any_cast;

template <typename T, typename... Types> 
void Alert(T var1,Types... var2) 
{ 

    std::vector<boost::any> a(  {var1,var2...});

    for (int i = 0; i < a.size();i++)
    {

    if (a[i].type() == typeid(int))
    {
        std::cout << "int "  << boost::any_cast<int> (a[i]) << std::endl;
    }
    if (a[i].type() == typeid(double))
    {
        std::cout << "double "  << boost::any_cast<double> (a[i]) << std::endl;
    }
    if (a[i].type() == typeid(const char*))
    {
        std::cout << "char* " << boost::any_cast<const char*> (a[i]) <<std::endl;
    }
    // etc
    }

} 


void main()
{
    Alert("something",0,0,0.3);
}

How to take last four characters from a varchar?

You can select last characters with -

WHERE SUBSTR('Hello world', -4)

Checking if a variable is initialized

There's no reasonable way to check whether a value has been initialized.

If you care about whether something has been initialized, instead of trying to check for it, put code into the constructor(s) to ensure that they are always initialized and be done with it.

Make div (height) occupy parent remaining height

Abstract

I didn't find a fully satisfying answer so I had to find it out myself.

My requirements:

  • the element should take exactly the remaining space either when its content size is smaller or bigger than the remaining space size (in the second case scrollbar should be shown);
  • the solution should work when the parent height is computed, and not specified;
  • calc() should not be used as the remaining element shouldn't know anything about another element sizes;
  • modern and familar layout technique such as flexboxes should be used.

The solution

  • Turn into flexboxes all direct parents with computed height (if any) and the next parent whose height is specified;
  • Specify flex-grow: 1 to all direct parents with computed height (if any) and the element so they will take up all remaining space when the element content size is smaller;
  • Specify flex-shrink: 0 to all flex items with fixed height so they won't become smaller when the element content size is bigger than the remaining space size;
  • Specify overflow: hidden to all direct parents with computed height (if any) to disable scrolling and forbid displaying overflow content;
  • Specify overflow: auto to the element to enable scrolling inside it.

JSFiddle (element has direct parents with computed height)

JSFiddle (simple case: no direct parents with computed height)

Splitting a dataframe string column into multiple different columns

We could use tidyr::extract()

x <- c("F.US.CLE.V13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", 
  "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", 
  "F.US.DL.U13", "F.US.DL.U13", "F.US.DL.U13", "F.US.DL.Z13", "F.US.DL.Z13"
)


library(tidyr)
extract(tibble(data=x),"data", regex = "^(.*?)\\.(.*?)\\.(.*?)\\.(.*?)$",into = LETTERS[1:4])
#> # A tibble: 13 x 4
#>    A     B     C     D    
#>    <chr> <chr> <chr> <chr>
#>  1 F     US    CLE   V13  
#>  2 F     US    CA6   U13  
#>  3 F     US    CA6   U13  
#>  4 F     US    CA6   U13  
#>  5 F     US    CA6   U13  
#>  6 F     US    CA6   U13  
#>  7 F     US    CA6   U13  
#>  8 F     US    CA6   U13  
#>  9 F     US    DL    U13  
#> 10 F     US    DL    U13  
#> 11 F     US    DL    U13  
#> 12 F     US    DL    Z13  
#> 13 F     US    DL    Z13

Another option is to use unglue::unglue_data()

# remotes::install_github("moodymudskipper/unglue")
library(unglue)
unglue_data(x,"{A}.{B}.{C}.{D}")
#>    A  B   C   D
#> 1  F US CLE V13
#> 2  F US CA6 U13
#> 3  F US CA6 U13
#> 4  F US CA6 U13
#> 5  F US CA6 U13
#> 6  F US CA6 U13
#> 7  F US CA6 U13
#> 8  F US CA6 U13
#> 9  F US  DL U13
#> 10 F US  DL U13
#> 11 F US  DL U13
#> 12 F US  DL Z13
#> 13 F US  DL Z13

Created on 2019-09-14 by the reprex package (v0.3.0)

Removing legend on charts with chart.js v2

You simply need to add that line legend: { display: false }

Cast from VARCHAR to INT - MySQL

For casting varchar fields/values to number format can be little hack used:

SELECT (`PROD_CODE` * 1) AS `PROD_CODE` FROM PRODUCT`

How do I rename a Git repository?

Open git repository on browser, got to "Setttings", you can see rename button.

Input new "Repository Name" and click "Rename" button.

How can I check the size of a collection within a Django template?

You can try with:

{% if theList.object_list.count > 0 %}
    blah, blah...
{% else %}
    blah, blah....
{% endif %} 

Plotting two variables as lines using ggplot2 on the same graph

Using your data:

test_data <- data.frame(
var0 = 100 + c(0, cumsum(runif(49, -20, 20))),
var1 = 150 + c(0, cumsum(runif(49, -10, 10))),
Dates = seq.Date(as.Date("2002-01-01"), by="1 month", length.out=100))

I create a stacked version which is what ggplot() would like to work with:

stacked <- with(test_data,
                data.frame(value = c(var0, var1),
                           variable = factor(rep(c("Var0","Var1"),
                                                 each = NROW(test_data))),
                           Dates = rep(Dates, 2)))

In this case producing stacked was quite easy as we only had to do a couple of manipulations, but reshape() and the reshape and reshape2 might be useful if you have a more complex real data set to manipulate.

Once the data are in this stacked form, it only requires a simple ggplot() call to produce the plot you wanted with all the extras (one reason why higher-level plotting packages like lattice and ggplot2 are so useful):

require(ggplot2)
p <- ggplot(stacked, aes(Dates, value, colour = variable))
p + geom_line()

I'll leave it to you to tidy up the axis labels, legend title etc.

HTH

How to disable a link using only CSS?

If you want to stick to just HTML/CSS on a form, another option is to use a button. Style it and set the disabled attribute.

E.g. http://jsfiddle.net/cFTxH/1/

What does '--set-upstream' do?

git branch --set-upstream <remote-branch>

sets the default remote branch for the current local branch.

Any future git pull command (with the current local branch checked-out),
will attempt to bring in commits from the <remote-branch> into the current local branch.


One way to avoid having to explicitly type --set-upstream is to use its shorthand flag -u as follows:

git push -u origin local-branch

This sets the upstream association for any future push/pull attempts automatically.
For more details, checkout this detailed explanation about upstream branches and tracking.


To avoid confusion, recent versions of git deprecate this somewhat ambiguous --set-upstream option in favour of a more verbose --set-upstream-to option with identical syntax and behaviour

git branch --set-upstream-to <origin/remote-branch>

Css transition from display none to display block, navigation with subnav

You can do this with animation-keyframe rather than transition. Change your hover declaration and add the animation keyframe, you might also need to add browser prefixes for -moz- and -webkit-. See https://developer.mozilla.org/en/docs/Web/CSS/@keyframes for more detailed info.

_x000D_
_x000D_
nav.main ul ul {_x000D_
    position: absolute;_x000D_
    list-style: none;_x000D_
    display: none;_x000D_
    opacity: 0;_x000D_
    visibility: hidden;_x000D_
    padding: 10px;_x000D_
    background-color: rgba(92, 91, 87, 0.9);_x000D_
    -webkit-transition: opacity 600ms, visibility 600ms;_x000D_
            transition: opacity 600ms, visibility 600ms;_x000D_
}_x000D_
_x000D_
nav.main ul li:hover ul {_x000D_
    display: block;_x000D_
    visibility: visible;_x000D_
    opacity: 1;_x000D_
    animation: fade 1s;_x000D_
}_x000D_
_x000D_
@keyframes fade {_x000D_
    0% {_x000D_
        opacity: 0;_x000D_
    }_x000D_
_x000D_
    100% {_x000D_
        opacity: 1;_x000D_
    }_x000D_
}
_x000D_
<nav class="main">_x000D_
    <ul>_x000D_
        <li>_x000D_
            <a href="">Lorem</a>_x000D_
            <ul>_x000D_
                <li><a href="">Ipsum</a></li>_x000D_
                <li><a href="">Dolor</a></li>_x000D_
                <li><a href="">Sit</a></li>_x000D_
                <li><a href="">Amet</a></li>_x000D_
            </ul>_x000D_
        </li>_x000D_
    </ul>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

Here is an update on your fiddle. https://jsfiddle.net/orax9d9u/1/

How is using "<%=request.getContextPath()%>" better than "../"

request.getContextPath()- returns root path of your application, while ../ - returns parent directory of a file.

You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.

Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.

<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>

PS- This is the one reason I can figure out. Don't know if there is any more significance to it.

Why is there no xrange function in Python3?

Python3's range is Python2's xrange. There's no need to wrap an iter around it. To get an actual list in Python3, you need to use list(range(...))

If you want something that works with Python2 and Python3, try this

try:
    xrange
except NameError:
    xrange = range

How to move an element into another element?

Old question but got here because I need to move content from one container to another including all the event listeners.

jQuery doesn't have a way to do it but standard DOM function appendChild does.

//assuming only one .source and one .target
$('.source').on('click',function(){console.log('I am clicked');});
$('.target')[0].appendChild($('.source')[0]);

Using appendChild removes the .source and places it into target including it's event listeners: https://developer.mozilla.org/en-US/docs/Web/API/Node.appendChild

error: invalid type argument of ‘unary *’ (have ‘int’)

Once you declare the type of a variable, you don't need to cast it to that same type. So you can write a=&b;. Finally, you declared c incorrectly. Since you assign it to be the address of a, where a is a pointer to int, you must declare it to be a pointer to a pointer to int.

#include <stdio.h>
int main(void)
{
    int b=10;
    int *a=&b;
    int **c=&a;
    printf("%d", **c);
    return 0;
} 

How to make two plots side-by-side using Python?

Change your subplot settings to:

plt.subplot(1, 2, 1)

...

plt.subplot(1, 2, 2)

The parameters for subplot are: number of rows, number of columns, and which subplot you're currently on. So 1, 2, 1 means "a 1-row, 2-column figure: go to the first subplot." Then 1, 2, 2 means "a 1-row, 2-column figure: go to the second subplot."

You currently are asking for a 2-row, 1-column (that is, one atop the other) layout. You need to ask for a 1-row, 2-column layout instead. When you do, the result will be:

side by side plot

In order to minimize the overlap of subplots, you might want to kick in a:

plt.tight_layout()

before the show. Yielding:

neater side by side plot

How I can filter a Datatable?

Hi we can use ToLower Method sometimes it is not filter.

EmployeeId = Session["EmployeeID"].ToString();
var rows = dtCrewList.AsEnumerable().Where
   (row => row.Field<string>("EmployeeId").ToLower()== EmployeeId.ToLower());

   if (rows.Any())
   {
        tblFiltered = rows.CopyToDataTable<DataRow>();
   }

Django Model() vs Model.objects.create()

The differences between Model() and Model.objects.create() are the following:


  1. INSERT vs UPDATE

    Model.save() does either INSERT or UPDATE of an object in a DB, while Model.objects.create() does only INSERT.

    Model.save() does

    • UPDATE If the object’s primary key attribute is set to a value that evaluates to True

    • INSERT If the object’s primary key attribute is not set or if the UPDATE didn’t update anything (e.g. if primary key is set to a value that doesn’t exist in the database).


  1. Existing primary key

    If primary key attribute is set to a value and such primary key already exists, then Model.save() performs UPDATE, but Model.objects.create() raises IntegrityError.

    Consider the following models.py:

    class Subject(models.Model):
       subject_id = models.PositiveIntegerField(primary_key=True, db_column='subject_id')
       name = models.CharField(max_length=255)
       max_marks = models.PositiveIntegerField()
    
    1. Insert/Update to db with Model.save()

      physics = Subject(subject_id=1, name='Physics', max_marks=100)
      physics.save()
      math = Subject(subject_id=1, name='Math', max_marks=50)  # Case of update
      math.save()
      

      Result:

      Subject.objects.all().values()
      <QuerySet [{'subject_id': 1, 'name': 'Math', 'max_marks': 50}]>
      
    2. Insert to db with Model.objects.create()

      Subject.objects.create(subject_id=1, name='Chemistry', max_marks=100)
      IntegrityError: UNIQUE constraint failed: m****t.subject_id
      

    Explanation: In the example, math.save() does an UPDATE (changes name from Physics to Math, and max_marks from 100 to 50), because subject_id is a primary key and subject_id=1 already exists in the DB. But Subject.objects.create() raises IntegrityError, because, again the primary key subject_id with the value 1 already exists.


  1. Forced insert

    Model.save() can be made to behave as Model.objects.create() by using force_insert=True parameter: Model.save(force_insert=True).


  1. Return value

    Model.save() return None where Model.objects.create() return model instance i.e. package_name.models.Model


Conclusion: Model.objects.create() does model initialization and performs save() with force_insert=True.

Excerpt from the source code of Model.objects.create()

def create(self, **kwargs):
    """
    Create a new object with the given kwargs, saving it to the database
    and returning the created object.
    """
    obj = self.model(**kwargs)
    self._for_write = True
    obj.save(force_insert=True, using=self.db)
    return obj

For more details follow the links:

  1. https://docs.djangoproject.com/en/stable/ref/models/querysets/#create

  2. https://github.com/django/django/blob/2d8dcba03aae200aaa103ec1e69f0a0038ec2f85/django/db/models/query.py#L440

How to debug ORA-01775: looping chain of synonyms?

Try this select to find the problematic synonyms, it lists all synonyms that are pointing to an object that does not exist (tables,views,sequences,packages, procedures, functions)

SELECT *
FROM dba_synonyms
WHERE table_owner = 'USER'
    AND (
        NOT EXISTS (
            SELECT *
            FROM dba_tables
            WHERE dba_synonyms.table_name = dba_tables.TABLE_NAME
            )
        AND NOT EXISTS (
            SELECT *
            FROM dba_views
            WHERE dba_synonyms.table_name = dba_views.VIEW_NAME
            )
        AND NOT EXISTS (
            SELECT *
            FROM dba_sequences
            WHERE dba_synonyms.table_name = dba_sequences.sequence_NAME
            )
        AND NOT EXISTS (
            SELECT *
            FROM dba_dependencies
            WHERE type IN (
                    'PACKAGE'
                    ,'PROCEDURE'
                    ,'FUNCTION'
                    )
                AND dba_synonyms.table_name = dba_dependencies.NAME
            )
        )

How many bits is a "word"?

The second quote is correct, the size of a word varies from computer to computer. The ARM NEON architecture is an example of an architecture with 32-bit words, where 64-bit quantities are referred to as "doublewords" and 128-bit quantities are referred to as "quadwords":

A NEON operand can be a vector or a scalar. A NEON vector can be a 64-bit doubleword vector or a 128-bit quadword vector.

Normally speaking, 16-bit words are only found on 16-bit systems, like the Amiga 500.

git stash and git pull

When you have changes on your working copy, from command line do:

git stash 

This will stash your changes and clear your status report

git pull

This will pull changes from upstream branch. Make sure it says fast-forward in the report. If it doesn't, you are probably doing an unintended merge

git stash pop

This will apply stashed changes back to working copy and remove the changes from stash unless you have conflicts. In the case of conflict, they will stay in stash so you can start over if needed.

if you need to see what is in your stash

git stash list

How to read a file in other directory in python

In case you're not in the specified directory (i.e. direct), you should use (in linux):

x_file = open('path/to/direct/filename.txt')

Note the quotes and the relative path to the directory.

This may be your problem, but you also don't have permission to access that file. Maybe you're trying to open it as another user.

How to initialize struct?

  1. Will "length" ever deviate from the real length of "s". If the answer is no, then you don't need to store length, because strings store their length already, and you can just call s.Length.

  2. To get the syntax you asked for, you can implement an "implicit" operator like so:

    static implicit operator MyStruct(string s) {
        return new MyStruct(...);
    }
    
  3. The implicit operator will work, regardless of whether you make your struct mutable or not.

@Value annotation type casting to Integer from String

when use @Value, you should add @PropertySource annotation on Class, or specify properties holder in spring's xml file. eg.

@Component
@PropertySource("classpath:config.properties")
public class BusinessClass{
   @Value("${user.name}")
   private String name;
   @Value("${user.age}")
   private int age;
   @Value("${user.registed:false}")
   private boolean registed;
}

config.properties

user.name=test
user.age=20
user.registed=true

this works!

Of course, you can use placeholder xml configuration instead of annotation. spring.xml

<context:property-placeholder location="classpath:config.properties"/>

Python and SQLite: insert into table

This will work for a multiple row df having the dataframe as df with the same name of the columns in the df as the db.

tuples = list(df.itertuples(index=False, name=None))

columns_list = df.columns.tolist()
marks = ['?' for _ in columns_list]
columns_list = f'({(",".join(columns_list))})'
marks = f'({(",".join(marks))})'

table_name = 'whateveryouwant'

c.executemany(f'INSERT OR REPLACE INTO {table_name}{columns_list} VALUES {marks}', tuples)
conn.commit()

adding directory to sys.path /PYTHONPATH

Temporarily changing dirs works well for importing:

cwd = os.getcwd()
os.chdir(<module_path>)
import <module>
os.chdir(cwd)

What are the most common font-sizes for H1-H6 tags

Headings are normally bold-faced; that has been turned off for this demonstration of size correspondence. MSIE and Opera interpret these sizes the same, but note that Gecko browsers and Chrome interpret Heading 6 as 11 pixels instead of 10 pixels/font size 1, and Heading 3 as 19 pixels instead of 18 pixels/font size 4 (though it's difficult to tell the difference even in a direct comparison and impossible in use). It seems Gecko also limits text to no smaller than 10 pixels.

What are the best use cases for Akka framework

We use Akka in spoken dialog systems (primetalk). Both internally and externally. In order to simultaneously run a lot of telephony channels on a single cluster node it is obviously necessary to have some multithreading framework. Akka works just perfect. We have previous nightmare with the java-concurrency. And with Akka it is just like a swing — it simply works. Robust and reliable. 24*7, non-stop.

Inside a channel we have real-time stream of events that are processed in parallel. In particular: - lengthy automatic speech recognition — is done with an actor; - audio output producer that mixes a few audio sources (including synthesized speech); - text-to-speech conversion is a separate set of actors shared between channels; - semantic and knowledge processing.

To make interconnections of complex signal processing we use SynapseGrid. It has the benefit of compile-time checking of the DataFlow in the complex actor systems.

Return current date plus 7 days

Here is how you can do it using strtotime(),

<?php
    $date = strtotime("3 October 2005");
    $d = strtotime("+7 day", $date);
    echo "Created date is " . date("Y-m-d h:i:sa", $d) . "<br>";
?>

Disable autocomplete via CSS

You can't use CSS to disable autocomplete, but you can use HTML:

<input type="text" autocomplete="false" />

Technically you can replace false with any invalid value and it'll work. This iOS the only solution I've found which also works in Edge.

Cannot read property 'length' of null (javascript)

if (capital.touched && capital != undefined && capital.length < 1 ) { 
//capital does exists
}

How can I autoformat/indent C code in vim?

Try the following keystrokes:

gg=G

Explanation: gg goes to the top of the file, = is a command to fix the indentation and G tells it to perform the operation to the end of the file.

Running a cron every 30 seconds

No need for two cron entries, you can put it into one with:

* * * * * /bin/bash -l -c "/path/to/executable; sleep 30 ; /path/to/executable"

so in your case:

* * * * * /bin/bash -l -c "cd /srv/last_song/releases/20120308133159 && script/rails runner -e production '\''Song.insert_latest'\'' ; sleep 30 ; cd /srv/last_song/releases/20120308133159 && script/rails runner -e production '\''Song.insert_latest'\''"

python location on mac osx

On Mac OS X, it's in the Python framework in /System/Library/Frameworks/Python.framework/Resources.

Full path is:

/System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python

Btw it's easy to find out where you can find a specific binary: which Python will show you the path of your Python binary (which is probably the same as I posted above).

How to install and use "make" in Windows?

  1. Install Msys2 http://www.msys2.org
  2. Follow installation instructions
  3. Install make with $ pacman -S make gettext base-devel
  4. Add C:\msys64\usr\bin\ to your path

Need to find element in selenium by css

By.cssSelector(".ban") or By.cssSelector(".hot") or By.cssSelector(".ban.hot") should all select it unless there is another element that has those classes.

In CSS, .name means find an element that has a class with name. .foo.bar.baz means to find an element that has all of those classes (in the same element).

However, each of those selectors will select only the first element that matches it on the page. If you need something more specific, please post the HTML of the other elements that have those classes.

Is it possible to read the value of a annotation in java?

In common case you have private access for fields, so you CAN'T use getFields in reflection. Instead of this you should use getDeclaredFields

So, firstly, you should be aware if your Column annotation has the runtime retention:

@Retention(RetentionPolicy.RUNTIME)
@interface Column {
}

After that you can do something like this:

for (Field f: MyClass.class.getDeclaredFields()) {
   Column column = f.getAnnotation(Column.class);
       // ...
}

Obviously, you would like to do something with field - set new value using annotation value:

Column annotation = f.getAnnotation(Column.class);
if (annotation != null) {
    new PropertyDescriptor(f.getName(), Column.class).getWriteMethod().invoke(
        object,
        myCoolProcessing(
            annotation.value()
        )
    );
}

So, full code can be looked like this:

for (Field f : MyClass.class.getDeclaredFields()) {
    Column annotation = f.getAnnotation(Column.class);
    if (annotation != null)
        new PropertyDescriptor(f.getName(), Column.class).getWriteMethod().invoke(
                object,
                myCoolProcessing(
                        annotation.value()
                )
        );
}

What function is to replace a substring from a string in C?

There isn't one.

You'd need to roll your own using something like strstr and strcat or strcpy.

MySQL load NULL values from CSV data

The behaviour is different depending upon the database configuration. In the strict mode this would throw an error else a warning. Following query may be used for identifying the database configuration.

mysql> show variables like 'sql_mode';

Preferred method to store PHP arrays (json_encode vs serialize)

Before you make your final decision, be aware that the JSON format is not safe for associative arrays - json_decode() will return them as objects instead:

$config = array(
    'Frodo'   => 'hobbit',
    'Gimli'   => 'dwarf',
    'Gandalf' => 'wizard',
    );
print_r($config);
print_r(json_decode(json_encode($config)));

Output is:

Array
(
    [Frodo] => hobbit
    [Gimli] => dwarf
    [Gandalf] => wizard
)
stdClass Object
(
    [Frodo] => hobbit
    [Gimli] => dwarf
    [Gandalf] => wizard
)

PHP/regex: How to get the string value of HTML tag?

Since attribute values may contain a plain > character, try this regular expression:

$pattern = '/<'.preg_quote($tagname, '/').'(?:[^"'>]*|"[^"]*"|\'[^\']*\')*>(.*?)<\/'.preg_quote($tagname, '/').'>/s';

But regular expressions are not suitable for parsing non-regular languages like HTML. You should better use a parser like SimpleXML or DOMDocument.

MySQL high CPU usage

If this server is visible to the outside world, It's worth checking if it's having lots of requests to connect from the outside world (i.e. people trying to break into it)

What is the difference between const and readonly in C#?

Yet another gotcha: readonly values can be changed by "devious" code via reflection.

var fi = this.GetType()
             .BaseType
             .GetField("_someField", 
                       BindingFlags.Instance | BindingFlags.NonPublic);
fi.SetValue(this, 1);

Can I change a private readonly inherited field in C# using reflection?

#1146 - Table 'phpmyadmin.pma_recent' doesn't exist

I also have same problem.. I tried everything solution in google, but still error.

But, now i resolved it.

I've resolved with make give double slash like that:

//$cfg['Servers'][1]['table_uiprefs'] = 'pma__table_uiprefs';

It works!!

Assigning more than one class for one event

It's like this:

$('.tag.clickedTag').click(function (){ 
 // this will catch with two classes
}

$('.tag.clickedTag.otherclass').click(function (){ 
 // this will catch with three classes
}

$('.tag:not(.clickedTag)').click(function (){ 
 // this will catch tag without clickedTag
}

How do I convert a Swift Array to a String?

Swift 3

["I Love","Swift"].joined(separator:" ") // previously joinWithSeparator(" ")

References with text in LaTeX

Have a look to this wiki: LaTeX/Labels and Cross-referencing:

The hyperref package automatically includes the nameref package, and a similarly named command. It inserts text corresponding to the section name, for example:

\section{MyFirstSection}
\label{marker}
\section{MySecondSection} In section \nameref{marker} we defined...

Multiple inheritance for an anonymous class

An anonymous class usually implements an interface:

new Runnable() { // implements Runnable!
   public void run() {}
}

JFrame.addWindowListener( new WindowAdapter() { // extends  class
} );

If you mean whether you can implement 2 or more interfaces, than I think that's not possible. You can then make a private interface which combines the two. Though I cannot easily imagine why you would want an anonymous class to have that:

 public class MyClass {
   private interface MyInterface extends Runnable, WindowListener { 
   }

   Runnable r = new MyInterface() {
    // your anonymous class which implements 2 interaces
   }

 }

Deleting elements from std::set while iterating

This behaviour is implementation specific. To guarantee the correctness of the iterator you should use "it = numbers.erase(it);" statement if you need to delete the element and simply incerement iterator in other case.

Removing unwanted table cell borders with CSS

Set the cellspacing attribute of the table to 0.

You can also use the CSS style, border-spacing: 0, but only if you don't need to support older versions of IE.

C# - Fill a combo box with a DataTable

For example, i created a table :

DataTable dt = new DataTable ();
dt.Columns.Add("Title", typeof(string));
dt.Columns.Add("Value", typeof(int));

Add recorde to table :

DataRow row = dt.NewRow();
row["Title"] = "Price"
row["Value"] = 2000;
dt.Rows.Add(row);

or :

dt.Rows.Add("Price",2000);

finally :

combo.DataSource = dt;
combo.DisplayMember = "Title";
combo.ValueMember = "Value";

Formula to determine brightness of RGB color

The "Accepted" Answer is Incorrect and Incomplete

The only answers that are accurate are the @jive-dadson and @EddingtonsMonkey answers, and in support @nils-pipenbrinck. The other answers (including the accepted) are linking to or citing sources that are either wrong, irrelevant, obsolete, or broken.

Briefly:

  • sRGB must be LINEARIZED before applying the coefficients.
  • Luminance (L or Y) is linear as is light.
  • Perceived lightness (L*) is nonlinear as is human perception.
  • HSV and HSL are not even remotely accurate in terms of perception.
  • The IEC standard for sRGB specifies a threshold of 0.04045 it is NOT 0.03928 (that was from an obsolete early draft).
  • The be useful (i.e. relative to perception), Euclidian distances require a perceptually uniform Cartesian vector space such as CIELAB. sRGB is not one.

What follows is a correct and complete answer:

Because this thread appears highly in search engines, I am adding this answer to clarify the various misconceptions on the subject.

Luminance is a linear measure of light, spectrally weighted for normal vision but not adjusted for the non-linear perception of lightness. It can be a relative measure, Y as in CIEXYZ, or as L, an absolute measure in cd/m2 (not to be confused with L*).

Perceived lightness is used by some vision models such as CIELAB, here L* (Lstar) is a value of perceptual lightness, and is non-linear to approximate the human vision non-linear response curve.

Brightness is a perceptual attribute, it does not have a "physical" measure. However some color appearance models do have a value, usualy denoted as "Q" for perceived brightness, which is different than perceived lightness.

Luma ( prime) is a gamma encoded, weighted signal used in some video encodings (Y´I´Q´). It is not to be confused with linear luminance.

Gamma or transfer curve (TRC) is a curve that is often similar to the perceptual curve, and is commonly applied to image data for storage or broadcast to reduce perceived noise and/or improve data utilization (and related reasons).

To determine perceived lightness, first convert gamma encoded R´G´B´ image values to linear luminance (L or Y ) and then to non-linear perceived lightness (L*)


TO FIND LUMINANCE:

...Because apparently it was lost somewhere...

Step One:

Convert all sRGB 8 bit integer values to decimal 0.0-1.0

  vR = sR / 255;
  vG = sG / 255;
  vB = sB / 255;

Step Two:

Convert a gamma encoded RGB to a linear value. sRGB (computer standard) for instance requires a power curve of approximately V^2.2, though the "accurate" transform is:

sRGB to Linear

Where V´ is the gamma-encoded R, G, or B channel of sRGB.
Pseudocode:

function sRGBtoLin(colorChannel) {
        // Send this function a decimal sRGB gamma encoded color value
        // between 0.0 and 1.0, and it returns a linearized value.

    if ( colorChannel <= 0.04045 ) {
            return colorChannel / 12.92;
        } else {
            return pow((( colorChannel + 0.055)/1.055),2.4));
        }
    }

Step Three:

To find Luminance (Y) apply the standard coefficients for sRGB:

Apply coefficients Y = R * 0.2126 + G * 0.7152 + B *  0.0722

Pseudocode using above functions:

Y = (0.2126 * sRGBtoLin(vR) + 0.7152 * sRGBtoLin(vG) + 0.0722 * sRGBtoLin(vB))

TO FIND PERCEIVED LIGHTNESS:

Step Four:

Take luminance Y from above, and transform to L*

L* from Y equation
Pseudocode:

function YtoLstar(Y) {
        // Send this function a luminance value between 0.0 and 1.0,
        // and it returns L* which is "perceptual lightness"

    if ( Y <= (216/24389) {       // The CIE standard states 0.008856 but 216/24389 is the intent for 0.008856451679036
            return Y * (24389/27);  // The CIE standard states 903.3, but 24389/27 is the intent, making 903.296296296296296
        } else {
            return pow(Y,(1/3)) * 116 - 16;
        }
    }

L* is a value from 0 (black) to 100 (white) where 50 is the perceptual "middle grey". L* = 50 is the equivalent of Y = 18.4, or in other words an 18% grey card, representing the middle of a photographic exposure (Ansel Adams zone V).

References:

IEC 61966-2-1:1999 Standard
Wikipedia sRGB
Wikipedia CIELAB
Wikipedia CIEXYZ
Charles Poynton's Gamma FAQ

Pattern matching using a wildcard

If you really do want to use wildcards to identify specific variables, then you can use a combination of ls() and grep() as follows:

l = ls()
vars.with.result <- l[grep("result", l)]

replace String with another in java

Replacing one string with another can be done in the below methods

Method 1: Using String replaceAll

 String myInput = "HelloBrother";
 String myOutput = myInput.replaceAll("HelloBrother", "Brother"); // Replace hellobrother with brother
 ---OR---
 String myOutput = myInput.replaceAll("Hello", ""); // Replace hello with empty
 System.out.println("My Output is : " +myOutput);       

Method 2: Using Pattern.compile

 import java.util.regex.Pattern;
 String myInput = "JAVAISBEST";
 String myOutputWithRegEX = Pattern.compile("JAVAISBEST").matcher(myInput).replaceAll("BEST");
 ---OR -----
 String myOutputWithRegEX = Pattern.compile("JAVAIS").matcher(myInput).replaceAll("");
 System.out.println("My Output is : " +myOutputWithRegEX);           

Method 3: Using Apache Commons as defined in the link below:

http://commons.apache.org/proper/commons-lang/javadocs/api-z.1/org/apache/commons/lang3/StringUtils.html#replace(java.lang.String, java.lang.String, java.lang.String)

REFERENCE

How to count the number of rows in excel with data?

These would both work as well, letting Excel define the last time it sees data

numofrows = destsheet.UsedRange.SpecialCells(xlLastCell).row

numofrows = destsheet.Cells.SpecialCells(xlLastCell).row

Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified

I ran into this problem when I simply mistyped my jdbc url in application.properties. Hope this helps someone: before:

spring.datasource.url=jdbc://localhost:3306/test

after:

spring.datasource.url=jdbc:mysql://localhost:3306/test

Allowed characters in filename

Here is the code to clean file name in python.

import unicodedata

def clean_name(name, replace_space_with=None):
    """
    Remove invalid file name chars from the specified name

    :param name: the file name
    :param replace_space_with: if not none replace space with this string
    :return: a valid name for Win/Mac/Linux
    """

    # ref: https://en.wikipedia.org/wiki/Filename
    # ref: https://stackoverflow.com/questions/4814040/allowed-characters-in-filename
    # No control chars, no: /, \, ?, %, *, :, |, ", <, >

    # remove control chars
    name = ''.join(ch for ch in name if unicodedata.category(ch)[0] != 'C')

    cleaned_name = re.sub(r'[/\\?%*:|"<>]', '', name)
    if replace_space_with is not None:
        return cleaned_name.replace(' ', replace_space_with)
    return cleaned_name

linux find regex

You should have a look on the -regextype argument of find, see manpage:

      -regextype type
          Changes the regular expression syntax understood by -regex and -iregex 
          tests which occur later on the command line.  Currently-implemented  
          types  are  emacs (this is the default), posix-awk, posix-basic, 
          posix-egrep and posix-extended. 

I guess the emacs type doesn't support the [[:digit:]] construct. I tried it with posix-extended and it worked as expected:

find -regextype posix-extended -regex '.*[1234567890]'
find -regextype posix-extended -regex '.*[[:digit:]]'

Set an empty DateTime variable

You may want to use a nullable datetime. Datetime? someDate = null;

You may find instances of people using DateTime.Max or DateTime.Min in such instances, but I highly doubt you want to do that. It leads to bugs with edge cases, code that's harder to read, etc.

Remove element by id

For removing one element:

 var elem = document.getElementById("yourid");
 elem.parentElement.removeChild(elem);

For removing all the elements with for example a certain class name:

 var list = document.getElementsByClassName("yourclassname");
 for(var i = list.length - 1; 0 <= i; i--)
 if(list[i] && list[i].parentElement)
 list[i].parentElement.removeChild(list[i]);

How to refresh an IFrame using Javascript?

If you have Multiple iFrames inside the page, then this script might be useful. I am asuming there is a specific value in the iFrame source which can be used to find the specific iFrame.

var iframes = document.getElementsByTagName('iframe');
var yourIframe = null
for(var i=0; i < iframes.length ;i++){
    var source =  iframes[i].attributes.src.nodeValue;
    if(source.indexOf('/yourSorce') > -1){
        yourIframe = iframes[i];
    }   
}
var iSource = yourIframe.attributes.src.nodeValue;
yourIframe.src = iSource;

Replace "/yourSource" with value you need.

Converting datetime.date to UTC timestamp in Python

Using the arrow package:

>>> import arrow
>>> arrow.get(2010, 12, 31).timestamp
1293753600
>>> time.gmtime(1293753600)
time.struct_time(tm_year=2010, tm_mon=12, tm_mday=31, 
    tm_hour=0, tm_min=0, tm_sec=0, 
    tm_wday=4, tm_yday=365, tm_isdst=0)

Is it possible to create a File object from InputStream

Since Java 7, you can do it in one line even without using any external libraries:

Files.copy(inputStream, outputPath, StandardCopyOption.REPLACE_EXISTING);

See the API docs.

What are all the user accounts for IIS/ASP.NET and how do they differ?

This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....

To cover the identities listed:

IIS_IUSRS:

This is analogous to the old IIS6 IIS_WPG group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.

IUSR:

This account is analogous to the old IUSR_<MACHINE_NAME> local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).

For more information about IIS_IUSRS and IUSR see:

Understanding Built-In User and Group Accounts in IIS 7

DefaultAppPool:

If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name> will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>. You also won't see these pool accounts in your computers User Manager. See the following for more information:

Application Pool Identities

ASP.NET v4.0: -

This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool above.

NETWORK SERVICE: -

The NETWORK SERVICE account is a built-in identity introduced on Windows 2003. NETWORK SERVICE is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).

In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" /> setting in web.config file locally (if that setting is locked then it would need to be done by an admin in the machine.config file).

Setting <identity impersonate="true"> is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).

In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR or a specific custom anonymous account.

LOCAL SERVICE:

The LOCAL SERVICE account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:

LocalService Account

LOCAL SYSTEM:

You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.

LocalSystem Account

In Practice:

In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity:

enter image description here

In the website you should then configure the Authentication feature:

enter image description here

Right click and edit the Anonymous Authentication entry:

enter image description here

Ensure that "Application pool identity" is selected:

enter image description here

When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0 pool permissions then you can either do this via Explorer:

enter image description here

Click the "Check Names" button:

enter image description here

Or you can do this using the ICACLS.EXE utility:

icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)

...or...if you site's application pool is called BobsCatPicBlogthen:

icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)

I hope this helps clear things up.

Update:

I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:

The difference between the 'Local System' account and the 'Network Service' account?

Create instance of generic type whose constructor requires a parameter?

You can use the following command:

 T instance = (T)typeof(T).GetConstructor(new Type[0]).Invoke(new object[0]);

Be sure to see the following reference.

Forward request headers from nginx proxy server

The problem is that '_' underscores are not valid in header attribute. If removing the underscore is not an option you can add to the server block:

underscores_in_headers on;

This is basically a copy and paste from @kishorer747 comment on @Fleshgrinder answer, and solution is from: https://serverfault.com/questions/586970/nginx-is-not-forwarding-a-header-value-when-using-proxy-pass/586997#586997

I added it here as in my case the application behind nginx was working perfectly fine, but as soon ngix was between my flask app and the client, my flask app would not see the headers any longer. It was kind of time consuming to debug.

How do a LDAP search/authenticate against this LDAP in Java

You can also use the following code :

package com.agileinfotech.bsviewer.ldap;

import java.util.Hashtable;
import java.util.ResourceBundle;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

public class LDAPLoginAuthentication {
    public LDAPLoginAuthentication() {
        // TODO Auto-generated constructor
    }

    ResourceBundle resBundle = ResourceBundle.getBundle("settings");

    @SuppressWarnings("unchecked")
    public String authenticateUser(String username, String password) {
        String strUrl = "success";
        Hashtable env = new Hashtable(11);
        boolean b = false;
        String Securityprinciple = "cn=" + username + "," + resBundle.getString("UserSearch");
        env.put(Context.INITIAL_CONTEXT_FACTORY, resBundle.getString("InitialContextFactory"));
        env.put(Context.PROVIDER_URL, resBundle.getString("Provider_url"));
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, Securityprinciple);
        env.put(Context.SECURITY_CREDENTIALS, password);

        try {
            // Create initial context
            DirContext ctx = new InitialDirContext(env);
            // Close the context when we're done
            b = true;
            ctx.close();

        } catch (NamingException e) {
            b = false;
        } finally {
            if (b) {
                strUrl = "success";
            } else {
                strUrl = "failer";
            }
        }
        return strUrl;
    }
}

TypeError: can only concatenate list (not "str") to list

I think what you want to do is add a new item to your list, so you have change the line newinv=inventory+str(add) with this one:

newinv = inventory.append(add)

What you are doing now is trying to concatenate a list with a string which is an invalid operation in Python.

However I think what you want is to add and delete items from a list, in that case your if/else block should be:

if selection=="use":
    print(inventory)
    remove=input("What do you want to use? ")
    inventory.remove(remove)
    print(inventory)

elif selection=="pickup":
    print(inventory)
    add=input("What do you want to pickup? ")
    inventory.append(add)
    print(inventory)

You don't need to build a new inventory list every time you add a new item.

Force download a pdf link using javascript/ajax/jquery

Use the HTML5 "download" attribute

<a href="iphone_user_guide.pdf" download="iPhone User's Guide.PDF">click me</a>

Warning: as of this writing, does not work in IE/Safari, see: caniuse.com/#search=download

Edit: If you're looking for an actual javascript solution please see lajarre's answer

Check if TextBox is empty and return MessageBox?

Becasue is a TextBox already initialized would be better to control if there is something in there outside the empty string (which is no null or empty string I am afraid). What I did is just check is there is something different than "", if so do the thing:

 if (TextBox.Text != "") //Something different than ""?
        {
            //Do your stuff
        }
 else
        {
            //Do NOT do your stuff
        }

Why do I get a "permission denied" error while installing a gem?

I think the problem happened when you use rbenv. Try the below commands to fix it.

rbenv shell {rb_version}
rbenv global {rb_version}
or 
rbenv local {rb_version}

PHP & localStorage;

localStorage is something that is kept on the client side. There is no data transmitted to the server side.

You can only get the data with JavaScript and you can send it to the server side with Ajax.

How to get a tab character?

I use <span style="display: inline-block; width: 2ch;">&#9;</span> for a two characters wide tab.

How to compare only Date without Time in DateTime types in Linq to SQL with Entity Framework?

DateTime dt1 = DateTime.Now.Date;
DateTime dt2 = Convert.ToDateTime(TextBox4.Text.Trim()).Date;
if (dt1 >= dt2)
{
    MessageBox.Show("Valid Date");
}
else
{
    MessageBox.Show("Invalid Date... Please Give Correct Date....");
}

Run php script as daemon process

Kevin van Zonneveld wrote a very nice detailed article on this, in his example he makes use of the System_Daemon PEAR package (last release date on 2009-09-02).

How can I delay a :hover effect in CSS?

You can use transitions to delay the :hover effect you want, if the effect is CSS-based.

For example

div{
    transition: 0s background-color;
}

div:hover{
    background-color:red;    
    transition-delay:1s;
}

this will delay applying the the hover effects (background-color in this case) for one second.


Demo of delay on both hover on and off:

_x000D_
_x000D_
div{_x000D_
    display:inline-block;_x000D_
    padding:5px;_x000D_
    margin:10px;_x000D_
    border:1px solid #ccc;_x000D_
    transition: 0s background-color;_x000D_
    transition-delay:1s;_x000D_
}_x000D_
div:hover{_x000D_
    background-color:red;_x000D_
}
_x000D_
<div>delayed hover</div>
_x000D_
_x000D_
_x000D_

Demo of delay only on hover on:

_x000D_
_x000D_
div{_x000D_
    display:inline-block;_x000D_
    padding:5px;_x000D_
    margin:10px;_x000D_
    border:1px solid #ccc;_x000D_
    transition: 0s background-color;_x000D_
}_x000D_
div:hover{_x000D_
    background-color:red;    _x000D_
    transition-delay:1s;_x000D_
}
_x000D_
<div>delayed hover</div>
_x000D_
_x000D_
_x000D_


Vendor Specific Extentions for Transitions and W3C CSS3 transitions

How to add reference to a method parameter in javadoc?

I guess you could write your own doclet or taglet to support this behaviour.

Taglet Overview

Doclet Overview

How to use JavaScript with Selenium WebDriver Java

If you want to read text of any element using javascript executor, you can do something like following code:

WebElement ele = driver.findElement(By.xpath("//div[@class='infaCompositeViewTitle']"));
String assets = (String) js.executeScript("return arguments[0].getElementsByTagName('span')[1].textContent;", ele);

In this example, I have following HTML fragment and I am reading "156".

<div class="infaCompositeViewTitle">
   <span>All Assets</span>
   <span>156</span>
</div>

Java image resize, maintain aspect ratio

Translated from here:

Dimension getScaledDimension(Dimension imageSize, Dimension boundary) {

    double widthRatio = boundary.getWidth() / imageSize.getWidth();
    double heightRatio = boundary.getHeight() / imageSize.getHeight();
    double ratio = Math.min(widthRatio, heightRatio);

    return new Dimension((int) (imageSize.width  * ratio),
                         (int) (imageSize.height * ratio));
}

You can also use imgscalr to resize images while maintaining aspect ratio:

BufferedImage resizeMe = ImageIO.read(new File("orig.jpg"));
Dimension newMaxSize = new Dimension(255, 255);
BufferedImage resizedImg = Scalr.resize(resizeMe, Method.QUALITY,
                                        newMaxSize.width, newMaxSize.height);

Combine hover and click functions (jQuery)?

You can use .bind() or .live() whichever is appropriate, but no need to name the function:

$('#target').bind('click hover', function () {
 // common operation
});

or if you were doing this on lots of element (not much sense for an IE unless the element changes):

$('#target').live('click hover', function () {
 // common operation
});

Note, this will only bind the first hover argument, the mouseover event, it won't hook anything to the mouseleave event.

How to delete files/subfolders in a specific directory at the command prompt in Windows

Use:

del %pathtofolder%\*.*   /s /f  /q

This deletes all files and subfolders in %pathtofolder%, including read-only files, and does not prompt for confirmation.

How to install Selenium WebDriver on Mac OS

First up you need to download Selenium jar files from http://www.seleniumhq.org/download/. Then you'd need an IDE, something like IntelliJ or Eclipse. Then you'll have to map your jar files to those IDEs. Then depending on which language/framework you choose, you'll have to download the relevant library files, for example, if you're using JUnit you'll have to download Junit 4.11 jar file. Finally don't forget to download the drivers for Chrome and Safari (firefox driver comes standard with selenium). Once done, you can start coding and testing your code with the browser of your choice.

How do I collapse a table row in Bootstrap?

You just need to set the table cell padding to zero. Here's a jsfiddle (using Bootstrap 2.3.2) with your code slightly modified:

http://jsfiddle.net/marciowerner/fhjgn7b5/4/

The javascript is optional and only needed if you want to use a cell padding other than zero.

_x000D_
_x000D_
$('.collapse').on('show.bs.collapse', function() {_x000D_
  $(this).parent().removeClass("zeroPadding");_x000D_
});_x000D_
_x000D_
$('.collapse').on('hide.bs.collapse', function() {_x000D_
  $(this).parent().addClass("zeroPadding");_x000D_
});
_x000D_
.zeroPadding {_x000D_
  padding: 0 !important;_x000D_
}
_x000D_
<head>_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>_x000D_
  <script type="text/javascript" src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>_x000D_
  <link rel="stylesheet" type="text/css" href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <table class="table table-bordered table-striped">_x000D_
    <tr>_x000D_
      <td>_x000D_
        <button type="button" class="btn" data-toggle="collapse" data-target="#collapseme">Click to expand</button>_x000D_
      </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td class="zeroPadding">_x000D_
        <div class="collapse out" id="collapseme">Should be collapsed</div>_x000D_
      </td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Rails 3 execute custom sql query without a model

I'd recommend using ActiveRecord::Base.connection.exec_query instead of ActiveRecord::Base.connection.execute which returns a ActiveRecord::Result (available in rails 3.1+) which is a bit easier to work with.

Then you can access it in various the result in various ways like .rows, .each, or .to_hash

From the docs:

result = ActiveRecord::Base.connection.exec_query('SELECT id, title, body FROM posts')
result # => #<ActiveRecord::Result:0xdeadbeef>


# Get the column names of the result:
result.columns
# => ["id", "title", "body"]

# Get the record values of the result:
result.rows
# => [[1, "title_1", "body_1"],
      [2, "title_2", "body_2"],
      ...
     ]

# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
      {"id" => 2, "title" => "title_2", "body" => "body_2"},
      ...
     ]

# ActiveRecord::Result also includes Enumerable.
result.each do |row|
  puts row['title'] + " " + row['body']
end

note: copied my answer from here

What is the shortcut to Auto import all in Android Studio?

You can make short cut key for missing import in android studio which you like

  1. Click on file Menu
  2. Click on Settting
  3. click on key map
  4. Search for "auto-import"
  5. double click on auto import and select add keyboard short cut key
  6. that's all

enter image description here

enter image description here

enter image description here

Note: You can import single missing import using alt+enter which shown in pop up

enter image description here

How to move columns in a MySQL table?

Change column position:

ALTER TABLE Employees 
   CHANGE empName empName VARCHAR(50) NOT NULL AFTER department;

If you need to move it to the first position you have to use term FIRST at the end of ALTER TABLE CHANGE [COLUMN] query:

ALTER TABLE UserOrder 
   CHANGE order_id order_id INT(11) NOT NULL FIRST;

How to center align the ActionBar title in Android?

After a lot of research: This actually works:

 getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
 getActionBar().setCustomView(R.layout.custom_actionbar);
  ActionBar.LayoutParams p = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        p.gravity = Gravity.CENTER;

You have to define custom_actionbar.xml layout which is as per your requirement e.g. :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="#2e2e2e"
    android:orientation="vertical"
    android:gravity="center"
    android:layout_gravity="center">

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/top_banner"
        android:layout_gravity="center"
        />
</LinearLayout>

Can functions be passed as parameters?

Yes Go does accept first-class functions.

See the article "First Class Functions in Go" for useful links.

How do I convert array of Objects into one Object in JavaScript?

A clean way to do this using modern JavaScript is as follows:

const array = [
  { name: "something", value: "something" },
  { name: "somethingElse", value: "something else" },
];

const newObject = Object.assign({}, ...array.map(item => ({ [item.name]: item.value })));

// >> { something: "something", somethingElse: "something else" }

SQL Server Insert if not exists

For those looking for the fastest way, I recently came across these benchmarks where apparently using "INSERT SELECT... EXCEPT SELECT..." turned out to be the fastest for 50 million records or more.

Here's some sample code from the article (the 3rd block of code was the fastest):

INSERT INTO #table1 (Id, guidd, TimeAdded, ExtraData)
SELECT Id, guidd, TimeAdded, ExtraData
FROM #table2
WHERE NOT EXISTS (Select Id, guidd From #table1 WHERE #table1.id = #table2.id)
-----------------------------------
MERGE #table1 as [Target]
USING  (select Id, guidd, TimeAdded, ExtraData from #table2) as [Source]
(id, guidd, TimeAdded, ExtraData)
    on [Target].id =[Source].id
WHEN NOT MATCHED THEN
    INSERT (id, guidd, TimeAdded, ExtraData)
    VALUES ([Source].id, [Source].guidd, [Source].TimeAdded, [Source].ExtraData);
------------------------------
INSERT INTO #table1 (id, guidd, TimeAdded, ExtraData)
SELECT id, guidd, TimeAdded, ExtraData from #table2
EXCEPT
SELECT id, guidd, TimeAdded, ExtraData from #table1
------------------------------
INSERT INTO #table1 (id, guidd, TimeAdded, ExtraData)
SELECT #table2.id, #table2.guidd, #table2.TimeAdded, #table2.ExtraData
FROM #table2
LEFT JOIN #table1 on #table1.id = #table2.id
WHERE #table1.id is null

How to add elements of a Java8 stream into an existing List

The short answer is no (or should be no). EDIT: yeah, it's possible (see assylias' answer below), but keep reading. EDIT2: but see Stuart Marks' answer for yet another reason why you still shouldn't do it!

The longer answer:

The purpose of these constructs in Java 8 is to introduce some concepts of Functional Programming to the language; in Functional Programming, data structures are not typically modified, instead, new ones are created out of old ones by means of transformations such as map, filter, fold/reduce and many others.

If you must modify the old list, simply collect the mapped items into a fresh list:

final List<Integer> newList = list.stream()
                                  .filter(n -> n % 2 == 0)
                                  .collect(Collectors.toList());

and then do list.addAll(newList) — again: if you really must.

(or construct a new list concatenating the old one and the new one, and assign it back to the list variable—this is a little bit more in the spirit of FP than addAll)

As to the API: even though the API allows it (again, see assylias' answer) you should try to avoid doing that regardless, at least in general. It's best not to fight the paradigm (FP) and try to learn it rather than fight it (even though Java generally isn't a FP language), and only resort to "dirtier" tactics if absolutely needed.

The really long answer: (i.e. if you include the effort of actually finding and reading an FP intro/book as suggested)

To find out why modifying existing lists is in general a bad idea and leads to less maintainable code—unless you're modifying a local variable and your algorithm is short and/or trivial, which is out of the scope of the question of code maintainability—find a good introduction to Functional Programming (there are hundreds) and start reading. A "preview" explanation would be something like: it's more mathematically sound and easier to reason about to not modify data (in most parts of your program) and leads to higher level and less technical (as well as more human friendly, once your brain transitions away from the old-style imperative thinking) definitions of program logic.

Expected initializer before function name

Try adding a semi colon to the end of your structure:

 struct sotrudnik {
    string name;
    string speciality;
    string razread;
    int zarplata;
} //Semi colon here

Html5 Full screen video

From CSS

video {
    position: fixed; right: 0; bottom: 0;
    min-width: 100%; min-height: 100%;
    width: auto; height: auto; z-index: -100;
    background: url(polina.jpg) no-repeat;
    background-size: cover;
}

Count if two criteria match - EXCEL formula

If youR data was in A1:C100 then:

Excel - all versions

=SUMPRODUCT(--(A1:A100="M"),--(C1:C100="Yes"))

Excel - 2007 onwards

=COUNTIFS(A1:A100,"M",C1:C100,"Yes")

Can't connect to MySQL server on 'localhost' (10061)

You'll probably have to grant 'localhost' privileges to on the table to the user. See the 'GRANT' syntax documentation. Here's an example (from some C source).

"GRANT ALL PRIVILEGES ON %s.* TO '%s'@'localhost' IDENTIFIED BY '%s'";

That's the most common access problem with MySQL.

Other than that, you might check that the user you have defined to create your instance has full privileges, else the user cannot grant privileges.

Also, make sure the mysql service is started.

Make sure you don't have a third party firewall or Internet security service turned on.

Beyond that, there's several pages of the MySQL forum devoted to this: http://forums.mysql.com/read.php?11,9293,9609#msg-9609

Try reading that.

Windows task scheduler error 101 launch failure code 2147943785

I have the same today on Win7.x64, this solve it.

Right Click MyComputer > Manage > Local Users and Groups > Groups > Administrators double click > your name should be there, if not press add...

How do I grab an INI value within a shell script?

Bash does not provide a parser for these files. Obviously you can use an awk command or a couple of sed calls, but if you are bash-priest and don't want to use any other shell, then you can try the following obscure code:

#!/usr/bin/env bash
cfg_parser ()
{
    ini="$(<$1)"                # read the file
    ini="${ini//[/\[}"          # escape [
    ini="${ini//]/\]}"          # escape ]
    IFS=$'\n' && ini=( ${ini} ) # convert to line-array
    ini=( ${ini[*]//;*/} )      # remove comments with ;
    ini=( ${ini[*]/\    =/=} )  # remove tabs before =
    ini=( ${ini[*]/=\   /=} )   # remove tabs after =
    ini=( ${ini[*]/\ =\ /=} )   # remove anything with a space around =
    ini=( ${ini[*]/#\\[/\}$'\n'cfg.section.} ) # set section prefix
    ini=( ${ini[*]/%\\]/ \(} )    # convert text2function (1)
    ini=( ${ini[*]/=/=\( } )    # convert item to array
    ini=( ${ini[*]/%/ \)} )     # close array parenthesis
    ini=( ${ini[*]/%\\ \)/ \\} ) # the multiline trick
    ini=( ${ini[*]/%\( \)/\(\) \{} ) # convert text2function (2)
    ini=( ${ini[*]/%\} \)/\}} ) # remove extra parenthesis
    ini[0]="" # remove first element
    ini[${#ini[*]} + 1]='}'    # add the last brace
    eval "$(echo "${ini[*]}")" # eval the result
}

cfg_writer ()
{
    IFS=' '$'\n'
    fun="$(declare -F)"
    fun="${fun//declare -f/}"
    for f in $fun; do
        [ "${f#cfg.section}" == "${f}" ] && continue
        item="$(declare -f ${f})"
        item="${item##*\{}"
        item="${item%\}}"
        item="${item//=*;/}"
        vars="${item//=*/}"
        eval $f
        echo "[${f#cfg.section.}]"
        for var in $vars; do
            echo $var=\"${!var}\"
        done
    done
}

Usage:

# parse the config file called 'myfile.ini', with the following
# contents::
#   [sec2]
#   var2='something'
cfg.parser 'myfile.ini'

# enable section called 'sec2' (in the file [sec2]) for reading
cfg.section.sec2

# read the content of the variable called 'var2' (in the file
# var2=XXX). If your var2 is an array, then you can use
# ${var[index]}
echo "$var2"

Bash ini-parser can be found at The Old School DevOps blog site.

CentOS: Enabling GD Support in PHP Installation

Put the command

yum install php-gd

and restart the server (httpd, nginx, etc)

service httpd restart

Get a list of checked checkboxes in a div using jQuery

 var agencias = [];
 $('#Div input:checked').each(function(index, item){
 agencias.push(item.nextElementSibling.attributes.for.nodeValue);
 });

How to replace all spaces in a string

Simple code for replace all spaces

var str = 'How are you';
var replaced = str.split(' ').join('');

Out put: Howareyou

Show spinner GIF during an $http request in AngularJS?

Here are the current past AngularJS incantations:

angular.module('SharedServices', [])
    .config(function ($httpProvider) {
        $httpProvider.responseInterceptors.push('myHttpInterceptor');
        var spinnerFunction = function (data, headersGetter) {
            // todo start the spinner here
            //alert('start spinner');
            $('#mydiv').show();
            return data;
        };
        $httpProvider.defaults.transformRequest.push(spinnerFunction);
    })
// register the interceptor as a service, intercepts ALL angular ajax http calls
    .factory('myHttpInterceptor', function ($q, $window) {
        return function (promise) {
            return promise.then(function (response) {
                // do something on success
                // todo hide the spinner
                //alert('stop spinner');
                $('#mydiv').hide();
                return response;

            }, function (response) {
                // do something on error
                // todo hide the spinner
                //alert('stop spinner');
                $('#mydiv').hide();
                return $q.reject(response);
            });
        };
    });

//regular angular initialization continued below....
angular.module('myApp', [ 'myApp.directives', 'SharedServices']).
//.......

Here is the rest of it (HTML / CSS)....using

$('#mydiv').show(); 
$('#mydiv').hide(); 

to toggle it. NOTE: the above is used in the angular module at beginning of post

#mydiv {  
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
    z-index:1000;
    background-color:grey;
    opacity: .8;
 }

.ajax-loader {
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -32px; /* -1 * image width / 2 */
    margin-top: -32px;  /* -1 * image height / 2 */
    display: block;     
}

<div id="mydiv">
    <img src="lib/jQuery/images/ajax-loader.gif" class="ajax-loader"/>
</div>

Docker: How to use bash with an Alpine based docker image?

Alpine docker image doesn't have bash installed by default. You will need to add following commands to get bash:

RUN apk update && apk add bash

If youre using Alpine 3.3+ then you can just do

RUN apk add --no-cache bash

to keep docker image size small. (Thanks to comment from @sprkysnrky)

error: RPC failed; curl transfer closed with outstanding read data remaining

As above mentioned, first of all run your git command from bash adding the enhanced log directives in the beginning: GIT_TRACE=1 GIT_CURL_VERBOSE=1 git ...

e.g. GIT_CURL_VERBOSE=1 GIT_TRACE=1 git -c diff.mnemonicprefix=false -c core.quotepath=false fetch origin This will show you detailed error information.

How to detect a mobile device with JavaScript?

Testing for user agent is complex, messy and invariably fails. I also didn't find that the media match for "handheld" worked for me. The simplest solution was to detect if the mouse was available. And that can be done like this:

var result = window.matchMedia("(any-pointer:coarse)").matches;

That will tell you if you need to show hover items or not and anything else that requires a physical pointer. The sizing can then be done on further media queries based on width.

The following little library is a belt braces version of the query above, should cover most "are you a tablet or a phone with no mouse" scenarios.

https://patrickhlauke.github.io/touch/touchscreen-detection/

Media matches have been supported since 2015 and you can check the compatibility here: https://caniuse.com/#search=matchMedia

In short you should maintain variables relating to whether the screen is touch screen and also what size the screen is. In theory I could have a tiny screen on a mouse operated desktop.

submitting a GET form with query string params and hidden params disappear

You should include the two items (a and b) as hidden input elements as well as C.

"You tried to execute a query that does not include the specified aggregate function"

GROUP BY can be selected from Total row in query design view in MS Access.
If Total row not shown in design view (as in my case). You can go to SQL View and add GROUP By fname etc. Then Total row will automatically show in design view.
You have to select as Expression in this row for calculated fields.

What is the difference between JDK and JRE?

suppose, if you are a developer then your role is to develop program as well as to execute the program. so you must have environment for developing and executing, which is provided by JDK.

suppose, if you are a client then you don't have to worry about developing.Just you need is, an environment to run program and get result only, which is provided by JRE.

JRE executes the application but JVM reads the instructions line by line so it's interpreter.

JDK=JRE+Development Tools

JRE=JVM+Library Classes

Encrypt and decrypt a string in C#?

EDIT 2013-Oct: Although I've edited this answer over time to address shortcomings, please see jbtule's answer for a more robust, informed solution.

https://stackoverflow.com/a/10366194/188474

Original Answer:

Here's a working example derived from the "RijndaelManaged Class" documentation and the MCTS Training Kit.

EDIT 2012-April: This answer was edited to pre-pend the IV per jbtule's suggestion and as illustrated here:

http://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged%28v=vs.95%29.aspx

Good luck!

public class Crypto
{

    //While an app specific salt is not the best practice for
    //password based encryption, it's probably safe enough as long as
    //it is truly uncommon. Also too much work to alter this answer otherwise.
    private static byte[] _salt = __To_Do__("Add a app specific salt here");

    /// <summary>
    /// Encrypt the given string using AES.  The string can be decrypted using 
    /// DecryptStringAES().  The sharedSecret parameters must match.
    /// </summary>
    /// <param name="plainText">The text to encrypt.</param>
    /// <param name="sharedSecret">A password used to generate a key for encryption.</param>
    public static string EncryptStringAES(string plainText, string sharedSecret)
    {
        if (string.IsNullOrEmpty(plainText))
            throw new ArgumentNullException("plainText");
        if (string.IsNullOrEmpty(sharedSecret))
            throw new ArgumentNullException("sharedSecret");

        string outStr = null;                       // Encrypted string to return
        RijndaelManaged aesAlg = null;              // RijndaelManaged object used to encrypt the data.

        try
        {
            // generate the key from the shared secret and the salt
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

            // Create a RijndaelManaged object
            aesAlg = new RijndaelManaged();
            aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);

            // Create a decryptor to perform the stream transform.
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            // Create the streams used for encryption.
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                // prepend the IV
                msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
                msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }
                }
                outStr = Convert.ToBase64String(msEncrypt.ToArray());
            }
        }
        finally
        {
            // Clear the RijndaelManaged object.
            if (aesAlg != null)
                aesAlg.Clear();
        }

        // Return the encrypted bytes from the memory stream.
        return outStr;
    }

    /// <summary>
    /// Decrypt the given string.  Assumes the string was encrypted using 
    /// EncryptStringAES(), using an identical sharedSecret.
    /// </summary>
    /// <param name="cipherText">The text to decrypt.</param>
    /// <param name="sharedSecret">A password used to generate a key for decryption.</param>
    public static string DecryptStringAES(string cipherText, string sharedSecret)
    {
        if (string.IsNullOrEmpty(cipherText))
            throw new ArgumentNullException("cipherText");
        if (string.IsNullOrEmpty(sharedSecret))
            throw new ArgumentNullException("sharedSecret");

        // Declare the RijndaelManaged object
        // used to decrypt the data.
        RijndaelManaged aesAlg = null;

        // Declare the string used to hold
        // the decrypted text.
        string plaintext = null;

        try
        {
            // generate the key from the shared secret and the salt
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

            // Create the streams used for decryption.                
            byte[] bytes = Convert.FromBase64String(cipherText);
            using (MemoryStream msDecrypt = new MemoryStream(bytes))
            {
                // Create a RijndaelManaged object
                // with the specified key and IV.
                aesAlg = new RijndaelManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                // Get the initialization vector from the encrypted stream
                aesAlg.IV = ReadByteArray(msDecrypt);
                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))

                        // Read the decrypted bytes from the decrypting stream
                        // and place them in a string.
                        plaintext = srDecrypt.ReadToEnd();
                }
            }
        }
        finally
        {
            // Clear the RijndaelManaged object.
            if (aesAlg != null)
                aesAlg.Clear();
        }

        return plaintext;
    }

    private static byte[] ReadByteArray(Stream s)
    {
        byte[] rawLength = new byte[sizeof(int)];
        if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
        {
            throw new SystemException("Stream did not contain properly formatted byte array");
        }

        byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];
        if (s.Read(buffer, 0, buffer.Length) != buffer.Length)
        {
            throw new SystemException("Did not read byte array properly");
        }

        return buffer;
    }
}

Javascript change date into format of (dd/mm/yyyy)

Some JavaScript engines can parse that format directly, which makes the task pretty easy:

_x000D_
_x000D_
function convertDate(inputFormat) {_x000D_
  function pad(s) { return (s < 10) ? '0' + s : s; }_x000D_
  var d = new Date(inputFormat)_x000D_
  return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/')_x000D_
}_x000D_
_x000D_
console.log(convertDate('Mon Nov 19 13:29:40 2012')) // => "19/11/2012"
_x000D_
_x000D_
_x000D_

How do I partially update an object in MongoDB so the new object will overlay / merge with the existing one

I had success doing it this way:

db.collection.update(  { _id:...} , { $set: { 'key.another_key' : new_info  } } );

I have a function that handles my profile updates dynamically

function update(prop, newVal) {
  const str = `profile.${prop}`;
  db.collection.update( { _id:...}, { $set: { [str]: newVal } } );
}

Note: 'profile' is specific to my implementation, it is just the string of the key that you would like to modify.

How do I style radio buttons with images - laughing smiley for good, sad smiley for bad?

With pure html (no JS), you can't really substitute a radio-button for an image (at least, I don't think you can). You could, though use the following to make the same connection to the user:

<form action="" method="post">
    <fieldset>
       <input type="radio" name="feeling" id="feelingSad" value="sad" /><label for="feelingSad"><img src="path/to/sad.png" /></label>
       <label for="feelingHappy"><input type="radio" name="feeling" id="feelingHappy" value="happy" /><img src="path/to/happy.png" /></label>
    </fieldset>
</form>

CSS Equivalent of the "if" statement

I'd say the closest thing to "IF" in CSS are media queries, such as those you can use for responsive design. With media queries, you're saying things like, "If the screen is between 440px and 660px wide, do this". Read more about media queries here: http://www.w3schools.com/cssref/css3_pr_mediaquery.asp, and here's an example of how they look:

@media screen and (max-width: 300px) {
  body {
     background-color: lightblue;
  }
}

That's pretty much the extent of "IF" within CSS, except to move over to SASS/SCSS (as mentioned above).

I think your best bet is to change your classes / IDs within the scripting language, and then treat each of the class/ID options in your CSS. For instance, in PHP, it might be something like:

<?php
  if( A > B ){
echo '<div class="option-a">';
} 
    else{
echo '<div class="option-b">';
}
?>

Then your CSS can be like

.option-a {
background-color:red;
}
.option-b {
background-color:blue;
}

How do I run a file on localhost?

Looking at your other question I assume you are trying to run a php or asp file or something on your webserver and this is your first attempt in webdesign.

Once you have installed php correctly (which you probably did when you got XAMPP) just place whatever file you want under your localhost (/www/var/html perhaps?) and it should run. You can check this of course at localhost/file.php in your browser.

Change default global installation directory for node.js modules in Windows?

Find the current path of your global node package installation by following command.

npm list -g --depth=0

Change this path to correct path by following command.

npm set prefix C:\Users\username(Number)\AppData\Roaming\npm\node_modules

It worked for me. Read my previous answer for better understanding.

The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

  1. Why is this happening?

    The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, was officially deprecated in PHP v5.5.0 and removed in PHP v7.

    It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.

    The manual has contained warnings against its use in new code since June 2011.

  2. How can I fix it?

    As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.

    They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.

    Hashphp.org has an excellent tutorial on migrating from ext/mysql to PDO.

  3. I understand that it's possible to suppress deprecation errors by setting error_reporting in php.ini to exclude E_DEPRECATED:

    error_reporting = E_ALL ^ E_DEPRECATED
    

    What will happen if I do that?

    Yes, it is possible to suppress such error messages and continue using the old ext/mysql extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.

    Note also that this technique will suppress all E_DEPRECATED messages, not just those to do with the ext/mysql extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @—however this will suppress all errors raised by that expression, not just E_DEPRECATED ones.


What should you do?

  • You are starting a new project.

    There is absolutely no reason to use ext/mysql—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.

  • You have (your own) legacy codebase that currently depends upon ext/mysql.

    It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.

    • Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.

      Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.

    • The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.

      Consider whether you really need to upgrade to PHP v5.5 at this time.

      You should begin planning to replace ext/mysql with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.

      However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

  • You are using a third party project that depends upon ext/mysql.

    Consider whether you really need to upgrade to PHP v5.5 at this time.

    Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

    It is absolutely essential to perform regression testing.

Dynamically add item to jQuery Select2 control that uses AJAX

In case of Select2 Version 4+

it has changed syntax and you need to write like this:

// clear all option
$('#select_with_blank_data').html('').select2({data: [{id: '', text: ''}]});

// clear and add new option
$("#select_with_data").html('').select2({data: [
 {id: '', text: ''},
 {id: '1', text: 'Facebook'},
 {id: '2', text: 'Youtube'},
 {id: '3', text: 'Instagram'},
 {id: '4', text: 'Pinterest'}]});



//  append option
$("#select_with_data").append('<option value="5">Twitter</option>');
$("#select_with_data").val('5');
$("#select_with_data").trigger('change');

Styling Google Maps InfoWindow

google.maps.event.addListener(infowindow, 'domready', function() {

    // Reference to the DIV that wraps the bottom of infowindow
    var iwOuter = $('.gm-style-iw');

    /* Since this div is in a position prior to .gm-div style-iw.
     * We use jQuery and create a iwBackground variable,
     * and took advantage of the existing reference .gm-style-iw for the previous div with .prev().
    */
    var iwBackground = iwOuter.prev();

    // Removes background shadow DIV
    iwBackground.children(':nth-child(2)').css({'display' : 'none'});

    // Removes white background DIV
    iwBackground.children(':nth-child(4)').css({'display' : 'none'});

    // Moves the infowindow 115px to the right.
    iwOuter.parent().parent().css({left: '115px'});

    // Moves the shadow of the arrow 76px to the left margin.
    iwBackground.children(':nth-child(1)').attr('style', function(i,s){ return s + 'left: 76px !important;'});

    // Moves the arrow 76px to the left margin.
    iwBackground.children(':nth-child(3)').attr('style', function(i,s){ return s + 'left: 76px !important;'});

    // Changes the desired tail shadow color.
    iwBackground.children(':nth-child(3)').find('div').children().css({'box-shadow': 'rgba(72, 181, 233, 0.6) 0px 1px 6px', 'z-index' : '1'});

    // Reference to the div that groups the close button elements.
    var iwCloseBtn = iwOuter.next();

    // Apply the desired effect to the close button
    iwCloseBtn.css({opacity: '1', right: '38px', top: '3px', border: '7px solid #48b5e9', 'border-radius': '13px', 'box-shadow': '0 0 5px #3990B9'});

    // If the content of infowindow not exceed the set maximum height, then the gradient is removed.
    if($('.iw-content').height() < 140){
      $('.iw-bottom-gradient').css({display: 'none'});
    }

    // The API automatically applies 0.7 opacity to the button after the mouseout event. This function reverses this event to the desired value.
    iwCloseBtn.mouseout(function(){
      $(this).css({opacity: '1'});
    });
  });

//CSS put in stylesheet

.gm-style-iw {
  background-color: rgb(237, 28, 36);
    border: 1px solid rgba(72, 181, 233, 0.6);
    border-radius: 10px;
    box-shadow: 0 1px 6px rgba(178, 178, 178, 0.6);
    color: rgb(255, 255, 255) !important;
    font-family: gothambook;
    text-align: center;
    top: 15px !important;
    width: 150px !important;
}

Tkinter example code for multiple windows, why won't buttons load correctly?

#!/usr/bin/env python
import Tkinter as tk

from Tkinter import *

class windowclass():

        def __init__(self,master):
                self.master = master
                self.frame = tk.Frame(master)
                self.lbl = Label(master , text = "Label")
                self.lbl.pack()
                self.btn = Button(master , text = "Button" , command = self.command )
                self.btn.pack()
                self.frame.pack()

        def command(self):
                print 'Button is pressed!'

                self.newWindow = tk.Toplevel(self.master)
                self.app = windowclass1(self.newWindow)

class windowclass1():

        def __init__(self , master):
                self.master = master
                self.frame = tk.Frame(master)
                master.title("a")
                self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25 , command = self.close_window)
                self.quitButton.pack()
                self.frame.pack()


        def close_window(self):
                self.master.destroy()


root = Tk()

root.title("window")

root.geometry("350x50")

cls = windowclass(root)

root.mainloop()

Using SQL LOADER in Oracle to import CSV file

I hade a csv file named FAR_T_SNSA.csv that i wanted to import in oracle database directly. For this i have done the following steps and it worked absolutely fine. Here are the steps that u vand follow out:

HOW TO IMPORT CSV FILE IN ORACLE DATABASE ?

  1. Get a .csv format file that is to be imported in oracle database. Here this is named “FAR_T_SNSA.csv”
  2. Create a table in sql with same column name as there were in .csv file. create table Billing ( iocl_id char(10), iocl_consumer_id char(10));

  3. Create a Control file that contains sql*loder script. In notepad type the script as below and save this with .ctl extension, in selecting file type as All Types(*). Here control file is named as Billing. And the Script is as Follows:

    LOAD DATA
    INFILE 'D:FAR_T_SNSA.csv'
    INSERT INTO TABLE Billing
    FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
    TRAILING NULLCOLS
    (
    iocl_id,
    iocl_consumer_id
    )
    
  4. Now in Command prompt run command:

    Sqlldr UserId/Password
    Control = “ControlFileName” 
    --------------------------------
    Here ControlFileName is Billing.
    

Generate an integer sequence in MySQL

Here is a compact binary version of the technique used in other answers here:

select ((((((b7.0 << 1 | b6.0) << 1 | b5.0) << 1 | b4.0) 
                  << 1 | b3.0) << 1 | b2.0) << 1 | b1.0) << 1 | b0.0 as n
from (select 0 union all select 1) as b0,
     (select 0 union all select 1) as b1,
     (select 0 union all select 1) as b2,
     (select 0 union all select 1) as b3,
     (select 0 union all select 1) as b4,
     (select 0 union all select 1) as b5,
     (select 0 union all select 1) as b6,
     (select 0 union all select 1) as b7

There are no unique or sorting phases, no string to number conversion, no arithmetic operations, and each dummy table only has 2 rows, so it should be pretty fast.

This version uses 8 "bits" so it counts from 0 to 255, but you can easily tweak that.

Check if value exists in Postgres array

"Any" works well. Just make sure that the any keyword is on the right side of the equal to sign i.e. is present after the equal to sign.

Below statement will throw error: ERROR: syntax error at or near "any"

select 1 where any('{hello}'::text[]) = 'hello';

Whereas below example works fine

select 1 where 'hello' = any('{hello}'::text[]);

openssl s_client -cert: Proving a client certificate was sent to the server

I know this is an old question but it does not yet appear to have an answer. I've duplicated this situation, but I'm writing the server app, so I've been able to establish what happens on the server side as well. The client sends the certificate when the server asks for it and if it has a reference to a real certificate in the s_client command line. My server application is set up to ask for a client certificate and to fail if one is not presented. Here is the command line I issue:

Yourhostname here -vvvvvvvvvv s_client -connect <hostname>:443 -cert client.pem -key cckey.pem -CAfile rootcert.pem -cipher ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH -tls1 -state

When I leave out the "-cert client.pem" part of the command the handshake fails on the server side and the s_client command fails with an error reported. I still get the report "No client certificate CA names sent" but I think that has been answered here above.

The short answer then is that the server determines whether a certificate will be sent by the client under normal operating conditions (s_client is not normal) and the failure is due to the server not recognizing the CA in the certificate presented. I'm not familiar with many situations in which two-way authentication is done although it is required for my project.

You are clearly sending a certificate. The server is clearly rejecting it.

The missing information here is the exact manner in which the certs were created and the way in which the provider loaded the cert, but that is probably all wrapped up by now.

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

Swift Method, and supply a demo.

func topMostController() -> UIViewController {
    var topController: UIViewController = UIApplication.sharedApplication().keyWindow!.rootViewController!
    while (topController.presentedViewController != nil) {
        topController = topController.presentedViewController!
    }
    return topController
}

func demo() {
    let vc = ViewController()
    let nav = UINavigationController.init(rootViewController: vc)
    topMostController().present(nav, animated: true, completion: nil)
}

INSERT INTO vs SELECT INTO

SELECT INTO is typically used to generate temp tables or to copy another table (data and/or structure).

In day to day code you use INSERT because your tables should already exist to be read, UPDATEd, DELETEd, JOINed etc. Note: the INTO keyword is optional with INSERT

That is, applications won't normally create and drop tables as part of normal operations unless it is a temporary table for some scope limited and specific usage.

A table created by SELECT INTO will have no keys or indexes or constraints unlike a real, persisted, already existing table

The 2 aren't directly comparable because they have almost no overlap in usage

make bootstrap twitter dialog modal draggable

In my own case, i had to set backdrop and set the top and left properties before i could apply draggable function on the modal dialog. Maybe it might help someone ;)

if (!($('.modal.in').length)) {       
$('.modal-dialog').css({
     top: 0,
     left: 0
   });
}
$('#myModal').modal({
  backdrop: false,
   show: true
});

$('.modal-dialog').draggable({
  handle: ".modal-header"
});

How to serve an image using nodejs

_x000D_
_x000D_
//This method involves directly integrating HTML Code in the res.write
//first time posting to stack ...pls be kind

const express = require('express');
const app = express();
const https = require('https');

app.get("/",function(res,res){
    res.write("<img src="+image url / src +">");
    res.send();
});

app.listen(3000, function(req, res) {
  console.log("the server is onnnn");
});
_x000D_
_x000D_
_x000D_

How to convert latitude or longitude to meters?

Latitudes and longitudes specify points, not distances, so your question is somewhat nonsensical. If you're asking about the shortest distance between two (lat, lon) points, see this Wikipedia article on great-circle distances.

Unmarshaling nested JSON objects

Assign the values of nested json to struct until you know the underlying type of json keys:-

package main

import (
    "encoding/json"
    "fmt"
)

// Object
type Object struct {
    Foo map[string]map[string]string `json:"foo"`
    More string `json:"more"`
}

func main(){
    someJSONString := []byte(`{"foo":{ "bar": "1", "baz": "2" }, "more": "text"}`)
    var obj Object
    err := json.Unmarshal(someJSONString, &obj)
    if err != nil{
        fmt.Println(err)
    }
    fmt.Println("jsonObj", obj)
}

How do I use a char as the case in a switch-case?

charAt gets a character from a string, and you can switch on them since char is an integer type.

So to switch on the first char in the String hello,

switch (hello.charAt(0)) {
  case 'a': ... break;
}

You should be aware though that Java chars do not correspond one-to-one with code-points. See codePointAt for a way to reliably get a single Unicode codepoints.

Append date to filename in linux

a bit more convoluted solution that fully matches your spec

echo `expr $FILENAME : '\(.*\)\.[^.]*'`_`date +%d-%m-%y`.`expr $FILENAME : '.*\.\([^.]*\)'`

where first 'expr' extracts file name without extension, second 'expr' extracts extension

Best C# API to create PDF

Update:

I'm not sure when or if the license changed for the iText# library, but it is licensed under AGPL which means it must be licensed if included with a closed-source product. The question does not (currently) require free or open-source libraries. One should always investigate the license type of any library used in a project.


I have used iText# with success in .NET C# 3.5; it is a port of the open source Java library for PDF generation and it's free.

There is a NuGet package available for iTextSharp version 5 and the official developer documentation, as well as C# examples, can be found at itextpdf.com

Call Python function from MATLAB

With Matlab 2014b python libraries can be called directly from matlab. A prefix py. is added to all packet names:

>> wrapped = py.textwrap.wrap("example")

wrapped = 

  Python list with no properties.

    ['example']

How to properly set Column Width upon creating Excel file? (Column properties)

I normally do this in VB and its easier because Excel records macros in VB. So I normally go to Excel and save the macro I want to do.

So that's what I did now and I got this code:

Columns("E:E").ColumnWidth = 17.29;

Range("E3").Interior.Pattern = xlSolid;
Range("E3").Interior.PatternColorIndex = xlAutomatic;
Range("E3").Interior.Color = 65535;
Range("E3").Interior.TintAndShade = 0;
Range("E3").Interior.PatternTintAndShade = 0;

I think you can do something like this:

xlWorkSheet.Columns[5].ColumnWidth = 18;

For your last question what you need to do is loop trough the columns you want to set their width:

for (int i = 1; i <= 10; i++) // this will apply it from col 1 to 10
{
    xlWorkSheet.Columns[i].ColumnWidth = 18;
}

How to check for empty value in Javascript?

First, I would check what i gets initialized to, to see if the elements returned by getElementsByName are what you think they are. Maybe split the problem by trying it with a hard-coded name like timetemp0, without the concatenation. You can also run the code through a browser debugger (FireBug, Chrome Dev Tools, IE Dev Tools).

Also, for your if-condition, this should suffice:

if (!timetemp[0].value) {
    // The value is empty.
}
else {
    // The value is not empty.
}

The empty string in Javascript is a falsey value, so the logical negation of that will get you into the if-block.

Determine distance from the top of a div to top of window with javascript

I used this:

                              myElement = document.getElemenById("xyz");
Get_Offset_From_Start       ( myElement );  // returns positions from website's start position
Get_Offset_From_CurrentView ( myElement );  // returns positions from current scrolled view's TOP and LEFT

code:

function Get_Offset_From_Start (object, offset) { 
    offset = offset || {x : 0, y : 0};
    offset.x += object.offsetLeft;       offset.y += object.offsetTop;
    if(object.offsetParent) {
        offset = Get_Offset_From_Start (object.offsetParent, offset);
    }
    return offset;
}

function Get_Offset_From_CurrentView (myElement) {
    if (!myElement) return;
    var offset = Get_Offset_From_Start (myElement);
    var scrolled = GetScrolled (myElement.parentNode);
    var posX = offset.x - scrolled.x;   var posY = offset.y - scrolled.y;
    return {lefttt: posX , toppp: posY };
}
//helper
function GetScrolled (object, scrolled) {
    scrolled = scrolled || {x : 0, y : 0};
    scrolled.x += object.scrollLeft;    scrolled.y += object.scrollTop;
    if (object.tagName.toLowerCase () != "html" && object.parentNode) { scrolled=GetScrolled (object.parentNode, scrolled); }
    return scrolled;
}

    /*
    // live monitoring
    window.addEventListener('scroll', function (evt) {
        var Positionsss =  Get_Offset_From_CurrentView(myElement);  
        console.log(Positionsss);
    });
    */

How to wait 5 seconds with jQuery?

I realize that this is an old question, but here's a plugin to address this issue that someone might find useful.

https://github.com/madbook/jquery.wait

lets you do this:

$('#myElement').addClass('load').wait(5000).addClass('done');

The reason why you should use .wait instead of .delay is because not all jquery functions are supported by .delay and that .delay only works with animation functions. For example delay does not support .addClass and .removeClass

Or you can use this function instead.

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

sleep(5000);

Laravel-5 'LIKE' equivalent (Eloquent)

If you want to see what is run in the database use dd(DB::getQueryLog()) to see what queries were run.

Try this

BookingDates::where('email', Input::get('email'))
    ->orWhere('name', 'like', '%' . Input::get('name') . '%')->get();

Converting any object to a byte array in java

Yeah. Just use binary serialization. You have to have each object use implements Serializable but it's straightforward from there.

Your other option, if you want to avoid implementing the Serializable interface, is to use reflection and read and write data to/from a buffer using a process this one below:

/** 
 * Sets all int fields in an object to 0.
 *
 * @param obj The object to operate on.
 *
 * @throws RuntimeException If there is a reflection problem.
 */
 public static void initPublicIntFields(final Object obj) {
    try {
       Field[] fields = obj.getClass().getFields();
       for (int idx = 0; idx < fields.length; idx++) {
          if (fields[idx].getType() == int.class) {
              fields[idx].setInt(obj, 0);
          }
       }
    } catch (final IllegalAccessException ex) {
       throw new RuntimeException(ex);
    }
 }

Source.

How can I use mySQL replace() to replace strings in multiple records?

This will help you.

UPDATE play_school_data SET title= REPLACE(title, "&#39;", "'") WHERE title = "Elmer&#39;s Parade";

Result:

title = Elmer's Parade

How do I make my ArrayList Thread-Safe? Another approach to problem in Java?

You can change from ArrayList to Vector type, in which every method is synchronized.

private Vector finishingOrder;
//Make a Vector to hold RaceCar objects to determine winners
finishingOrder = new Vector(numberOfRaceCars);

Leading zeros for Int in Swift

For left padding add a string extension like this:

Swift 2.0 +

extension String {
    func padLeft (totalWidth: Int, with: String) -> String {
        let toPad = totalWidth - self.characters.count
        if toPad < 1 { return self }
        return "".stringByPaddingToLength(toPad, withString: with, startingAtIndex: 0) + self
    }
}

Swift 3.0 +

extension String {
    func padLeft (totalWidth: Int, with: String) -> String {
        let toPad = totalWidth - self.characters.count
        if toPad < 1 { return self }
        return "".padding(toLength: toPad, withPad: with, startingAt: 0) + self
    }
}

Using this method:

for myInt in 1...3 {
    print("\(myInt)".padLeft(totalWidth: 2, with: "0"))
}

How to deploy a war file in JBoss AS 7?

I built the following ant-task for deployment based on the jboss deployment docs:

<target name="deploy" depends="jboss.environment, buildwar">
    <!-- Build path for deployed war-file -->
    <property name="deployed.war" value="${jboss.home}/${jboss.deploy.dir}/${war.filename}" />

    <!-- remove current deployed war -->
    <delete file="${deployed.war}.deployed" failonerror="false" />
    <waitfor maxwait="10" maxwaitunit="second">
        <available file="${deployed.war}.undeployed" />
    </waitfor>
    <delete dir="${deployed.war}" />

    <!-- copy war-file -->
    <copy file="${war.filename}" todir="${jboss.home}/${jboss.deploy.dir}" />

    <!-- start deployment -->
    <echo>start deployment ...</echo>
    <touch file="${deployed.war}.dodeploy" />

    <!-- wait for deployment to complete -->
    <waitfor maxwait="10" maxwaitunit="second">
        <available file="${deployed.war}.deployed" />
    </waitfor>
    <echo>deployment ok!</echo>
</target>

${jboss.deploy.dir} is set to standalone/deployments

XAMPP Start automatically on Windows 7 startup

Try following Steps for Apache

  • Go to your XAMPP installation folder. Right-click xampp-control.exe. Click "Run as administrator"
  • Stop Apache service action port
  • Tick this (in snapshot) check box. It will ask if you want to install as service. Click "Yes".
  • Go to Windows Services by typing Window + R, then typing services.msc

  • Enter a new service name as Apache2 (or similar)

  • Set it as automatic, if you want it to run as startup.

Repeat the steps for the MySQL service

enter image description here

Set a default parameter value for a JavaScript function

If for some reason you are not on ES6 and are using lodash here is a concise way to default function parameters via _.defaultTo method:

_x000D_
_x000D_
var fn = function(a, b) {_x000D_
  a = _.defaultTo(a, 'Hi')_x000D_
  b = _.defaultTo(b, 'Mom!')_x000D_
_x000D_
  console.log(a, b)_x000D_
}_x000D_
_x000D_
fn()                 // Hi Mom!_x000D_
fn(undefined, null)  // Hi Mom!_x000D_
fn(NaN, NaN)         // Hi Mom!_x000D_
fn(1)                // 1 "Mom!"_x000D_
fn(null, 2)          // Hi 2_x000D_
fn(false, false)     // false false_x000D_
fn(0, 2)             // 0 2
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Which will set the default if the current value is NaN, null, or undefined

Mythical man month 10 lines per developer day - how close on large projects?

Without actually checking my copy of "The Mythical Man-Month" (everybody reading this should really have a copy readily available), there was a chapter in which Brooks looked at productivity by lines written. The interesting point, to him, was not the actual number of lines written per day, but the fact that it seemed to be roughly the same in assembler and in PL/I (I think that was the higher-level language used).

Brooks wasn't about to throw out some sort of arbitrary figure of productivity, but he was working from data on real projects, and for all I can remember they might have been 12 lines/day on the average.

He did point out that productivity could be expected to vary. He said that compilers were three times as hard as application programs, and operating systems three times as hard as compilers. (He seems to have liked using multipliers of three to separate categories.)

I don't know if he appreciated then the individual differences between programmer productivity (although in an order-of-magnitude argument he did postulate a factor of seven difference), but as we know superior productivity isn't just a matter of writing more code, but also writing the right code to do the job.

There's also the question of the environment. Brooks speculated a bit about what would make developers faster or slower. Like lots of people, he questioned whether the current fads (interactive debugging using time-sharing systems) were any better than the old ways (careful preplanning for a two-hour shot using the whole machine).

Given that, I would disregard any actual productivity number he came up with as useless; the continuing value of the book is in the principles and more general lessons that people persist in not learning. (Hey, if everybody had learned them, the book would be of historical interest only, much like all of Freud's arguments that there is something like a subconscious mind.)

Word-wrap in an HTML table

The only thing that needs to be done is add width to the <td> or the <div> inside the <td> depending on the layout you want to achieve.

eg:

<table style="width: 100%;" border="1"><tr>
<td><div style="word-wrap: break-word; width: 100px;">looooooooooodasdsdaasdasdasddddddddddddddddddddddddddddddasdasdasdsadng word</div></td>
<td><span style="display: inline;">Foo</span></td>
</tr></table>

or

 <table style="width: 100%;" border="1"><tr>
    <td width="100" ><div style="word-wrap: break-word; ">looooooooooodasdsdaasdasdasddddddddddddddddddddddddddddddasdasdasdsadng word</div></td>
    <td><span style="display: inline;">Foo</span></td>

</tr></table>

Change the "No file chosen":

you can use the following css code to hide (no file chosen)

HTML

<input type="file" name="page_logo" id="page_logo">

CSS

input[type="file"]:after {color: #fff}

MAKE SURE THE COLOR IS MATCHING THE BACKGROUND COLOR

How can I get a Unicode character's code?

In Java, char is technically a "16-bit integer", so you can simply cast it to int and you'll get it's code. From Oracle:

The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

So you can simply cast it to int.

char registered = '®';
System.out.println(String.format("This is an int-code: %d", (int) registered));
System.out.println(String.format("And this is an hexa code: %x", (int) registered));

Selecting only first-level elements in jquery

1

 $("ul.rootlist > target-element")
2   $("ul.rootlist").find(target-element).eq(0) (only one instance)
3   $("ul.rootlist").children(target-element)

there are probably many other ways

Update a column value, replacing part of a string

UPDATE yourtable
SET url = REPLACE(url, 'http://domain1.com/images/', 'http://domain2.com/otherfolder/')
WHERE url LIKE ('http://domain1.com/images/%');

relevant docs: http://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_replace

How do I start my app on startup?

For Android 10 there is background restrictions.

For android 10 and all version of android follow this steps to start an app after a restart or turn on mobile

Add this two permission in Android Manifest

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

Add this in your application tag

<receiver
        android:name=".BootReciever"
        android:enabled="true"
        android:exported="true"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
</receiver>

Add this class to start activity when boot up

public class BootReciever extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    if (Objects.equals(intent.getAction(), Intent.ACTION_BOOT_COMPLETED)) {
        Intent i = new Intent(context, SplashActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }
 }}

We need Draw overlay permission for android 10

so add this in your first activity

 private fun requestPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (!Settings.canDrawOverlays(this)) {
            val intent = Intent(
                Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                Uri.parse("package:" + this.packageName)
            )
            startActivityForResult(intent, 232)
        } else {
            //Permission Granted-System will work
        }
    }
}

Opening A Specific File With A Batch File?

@echo off
start %1

or if needed to escape the characters -

@echo off
start %%1

AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

yearofmoo did a great job at creating a reusable $safeApply function for us :

https://github.com/yearofmoo/AngularJS-Scope.SafeApply

Usage :

//use by itself
$scope.$safeApply();

//tell it which scope to update
$scope.$safeApply($scope);
$scope.$safeApply($anotherScope);

//pass in an update function that gets called when the digest is going on...
$scope.$safeApply(function() {

});

//pass in both a scope and a function
$scope.$safeApply($anotherScope,function() {

});

//call it on the rootScope
$rootScope.$safeApply();
$rootScope.$safeApply($rootScope);
$rootScope.$safeApply($scope);
$rootScope.$safeApply($scope, fn);
$rootScope.$safeApply(fn);

How to add System.Windows.Interactivity to project?

With Blend for Visual Studio, which is included in Visual Studio starting with version 2013, you can find the DLL in the following folder:

C:\Program Files (x86)\Microsoft SDKs\Expression\Blend\.NETFramework\v4.5\Libraries

You will have to add the reference to the System.Windows.Interactivity.dll yourself though, unless you use Blend for Visual Studio with an existing project to add functionality that makes use of the Interactivity namespace. In that case, Blend will add the reference automatically.

How to check if all elements of a list matches a condition?

Another way to use itertools.ifilter. This checks truthiness and process (using lambda)

Sample-

for x in itertools.ifilter(lambda x: x[2] == 0, my_list):
    print x

Get class labels from Keras functional model

You must use the labels index you have, here what I do for text classification:

# data labels = [1, 2, 1...]
labels_index = { "website" : 0, "money" : 1 ....} 
# to feed model
label_categories = to_categorical(np.asarray(labels)) 

Then, for predictions:

texts = ["hello, rejoins moi sur skype", "bonjour comment ça va ?", "tu me donnes de l'argent"]

sequences = tokenizer.texts_to_sequences(texts)

data = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH)

predictions = model.predict(data)

t = 0

for text in texts:
    i = 0
    print("Prediction for \"%s\": " % (text))
    for label in labels_index:
        print("\t%s ==> %f" % (label, predictions[t][i]))
        i = i + 1
    t = t + 1

This gives:

Prediction for "hello, rejoins moi sur skype": 
    website ==> 0.759483
    money ==> 0.037091
    under ==> 0.010587
    camsite ==> 0.114436
    email ==> 0.075975
    abuse ==> 0.002428
Prediction for "bonjour comment ça va ?": 
    website ==> 0.433079
    money ==> 0.084878
    under ==> 0.048375
    camsite ==> 0.036674
    email ==> 0.369197
    abuse ==> 0.027798
Prediction for "tu me donnes de l'argent": 
    website ==> 0.006223
    money ==> 0.095308
    under ==> 0.003586
    camsite ==> 0.003115
    email ==> 0.884112
    abuse ==> 0.007655

How To Execute SSH Commands Via PHP

Use the ssh2 functions. Anything you'd do via an exec() call can be done directly using these functions, saving you a lot of connections and shell invocations.

I can't understand why this JAXB IllegalAnnotationException is thrown

I had this same issue, I was passing a spring bean back as a ResponseBody object. When I handed back an object created by new, all was good.

Postman: sending nested JSON object

Best way to do that:

  1. In the Headers, add the following key-values:

    Content-Type to applications/json
    Accept to applications/json
    
  2. Under body, click raw and dropdown type to application/json

Also PFA for the same

enter image description here

enter image description here

Can't install laravel installer via composer

I am using WSL with ubuntu 16.04 LTS version with php 7.3 and laravel 5.7

sudo apt-get install php7.3-zip

Work for me

How to increase an array's length

I would suggest you use an ArrayList as you won't have to worry about the length anymore. Once created, you can't modify an array size:

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.

(Source)

Handling urllib2's timeout? - Python

In Python 2.7.3:

import urllib2
import socket

class MyException(Exception):
    pass

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError as e:
    print type(e)    #not catch
except socket.timeout as e:
    print type(e)    #catched
    raise MyException("There was an error: %r" % e)

RedirectToAction with parameter

RedirectToAction with parameter:

return RedirectToAction("Action","controller", new {@id=id});

Gradle project refresh failed after Android Studio update

Although this has been answered a long time ago, I had the same problem with an app after updating to

Gradle 2.1.2

The solution I found (on top of the one given by @WarrenFaith was to:

File -> Synchronize

This solved all the errors generated by the Gradle update.

Cannot import XSSF in Apache POI

You did not described the environment, anyway, you should download apache poi libraries. If you are using eclipse , right click on your root project , so properties and in java build path add external jar and import in your project those libraries :

xmlbeans-2.6.0 ; poi-ooxml-schemas- ... ; poi-ooxml- ... ; poi- .... ;

Twitter Bootstrap: Print content of modal window

Heres a solution with no Javascript or plugin - just some css and one extra class in the markup. This solutions uses the fact that BootStrap adds a class to the body when a dialog is open. We use this class to then hide the body, and print only the dialog.

To ensure we can determine the main body of the page we need to contain everything within the main page content in a div - I've used id="mainContent". Sample Page layout below - with a main page and two dialogs

<body>
 <div class="container body-content">

  <div id="mainContent">
       main page stuff     
  </div>
  <!-- Dialog One -->
  <div class="modal fade in">
   <div class="modal-dialog">
    <div class="modal-content">
          ...
    </div>
   </div>
  </div>

  <!-- Dialog Two -->
  <div class="modal fade in">
   <div class="modal-dialog">
    <div class="modal-content">
          ...
    </div>
   </div>
  </div>

 </div>
</body>

Then in our CSS print media queries, I use display: none to hide everything I don't want displayed - ie the mainContent when a dialog is open. I also use a specific class noPrint to be used on any parts of the page that should not be displayed - say action buttons. Here I am also hiding the headers and footers. You may need to tweak it to get exactly want you want.

@media print {
    header, .footer, footer {
        display: none;
    }

    /* hide main content when dialog open */
    body.modal-open div.container.body-content div#mainContent {
        display: none;
    }

    .noPrint {
        display: none;
    }
}

How to specify in crontab by what user to run script?

You can also try using runuser (as root) to run a command as a different user

*/1 * * * * runuser php5 \
            --command="/var/www/web/includes/crontab/queue_process.php \
                       >> /var/www/web/includes/crontab/queue.log 2>&1"

See also: man runuser

exporting multiple modules in react.js

When you

import App from './App.jsx';

That means it will import whatever you export default. You can rename App class inside App.jsx to whatever you want as long as you export default it will work but you can only have one export default.

So you only need to export default App and you don't need to export the rest.

If you still want to export the rest of the components, you will need named export.

https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export

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

From an anonymous block? I'd like to now more about the situation where you think that to be required, because with subquery factoring clauses and inline views it's pretty rare that you need to resort to PL/SQL for anything other than the most complex situations.

If you can use a named procedure then use pipelined functions. Here's an example pulled from the documentation:

CREATE PACKAGE pkg1 AS
  TYPE numset_t IS TABLE OF NUMBER;
  FUNCTION f1(x NUMBER) RETURN numset_t PIPELINED;
END pkg1;
/

CREATE PACKAGE BODY pkg1 AS
-- FUNCTION f1 returns a collection of elements (1,2,3,... x)
FUNCTION f1(x NUMBER) RETURN numset_t PIPELINED IS
  BEGIN
    FOR i IN 1..x LOOP
      PIPE ROW(i);
    END LOOP;
    RETURN;
  END;
END pkg1;
/

-- pipelined function is used in FROM clause of SELECT statement
SELECT * FROM TABLE(pkg1.f1(5));

How do you create a Marker with a custom icon for google maps API v3?

marker = new google.maps.Marker({
    map:map,
    // draggable:true,
    // animation: google.maps.Animation.DROP,
    position: new google.maps.LatLng(59.32522, 18.07002),
    icon: 'http://cdn.com/my-custom-icon.png' // null = default icon
  });

CSS pseudo elements in React

Got a reply from @Vjeux over at the React team:

Normal HTML/CSS:

<div class="something"><span>Something</span></div>
<style>
    .something::after {
    content: '';
    position: absolute;
    -webkit-filter: blur(10px) saturate(2);
}
</style>

React with inline style:

render: function() {
    return (
        <div>
          <span>Something</span>
          <div style={{position: 'absolute', WebkitFilter: 'blur(10px) saturate(2)'}} />
        </div>
    );
},

The trick is that instead of using ::after in CSS in order to create a new element, you should instead create a new element via React. If you don't want to have to add this element everywhere, then make a component that does it for you.

For special attributes like -webkit-filter, the way to encode them is by removing dashes - and capitalizing the next letter. So it turns into WebkitFilter. Note that doing {'-webkit-filter': ...} should also work.

Angular directive how to add an attribute to the element?

You can try this:

<div ng-app="app">
    <div ng-controller="AppCtrl">
        <a my-dir ng-repeat="user in users" ng-click="fxn()">{{user.name}}</a>
    </div>
</div>

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

function AppCtrl($scope) {
        $scope.users = [{ name: 'John', id: 1 }, { name: 'anonymous' }];
        $scope.fxn = function () {
            alert('It works');
        };
    }

app.directive("myDir", function ($compile) {
    return {
        scope: {ngClick: '='}
    };
});
</script>

Rollback one specific migration in Laravel

Best way is to create a new migration and make required changes in that.

Worst case workaround (if you have access to DB plus you are okay with a RESET of that table's data):

  1. Go to DB and delete/rename the migration entry for your-specific-migration
  2. Drop the table created by your-specific-migration
  3. Run php artisan migrate --path=/database/migrations/your-specific-migration.php

This will force laravel to run that specific migration as no entry about it exists in Laravel's migration history

UPDATE: The Laravel way (Thanks, @thiago-valente)

Run:

php artisan migrate:rollback --path=/database/migrations/your-specific-migration.php

and then:

php artisan migrate

This will re-run that particular migration

Flask Error: "Method Not Allowed The method is not allowed for the requested URL"

What is happening here is that database route does not accept any url methods.

I would try putting the url methods in the app route just like you have in the entry_page function:

@app.route('/entry', methods=['GET', 'POST'])
def entry_page():
    if request.method == 'POST':
        date = request.form['date']
        title = request.form['blog_title']
        post = request.form['blog_main']
        post_entry = models.BlogPost(date = date, title = title, post = post)
        db.session.add(post_entry)
        db.session.commit()
        return redirect(url_for('database'))
    else:
        return render_template('entry.html')

@app.route('/database', methods=['GET', 'POST'])        
def database():
    query = []
    for i in session.query(models.BlogPost):
        query.append((i.title, i.post, i.date))
    return render_template('database.html', query = query)

How to export settings?

You can now sync all your settings across devices with VSCode's built-in Settings Sync. It's found under Code > Preferences > Turn on Settings Sync...

Read more about it in the official docs here

.htaccess - how to force "www." in a generic way?

this worked like magic for me

RewriteCond %{HTTP_HOST} ^sitename.com [NC] RewriteRule ^(.*)$ https://www.sitename.com/$1 [L,R=301,NC]

Return True, False and None in Python

It's impossible to say without seeing your actual code. Likely the reason is a code path through your function that doesn't execute a return statement. When the code goes down that path, the function ends with no value returned, and so returns None.

Updated: It sounds like your code looks like this:

def b(self, p, data): 
    current = p 
    if current.data == data: 
        return True 
    elif current.data == 1:
        return False 
    else: 
        self.b(current.next, data)

That else clause is your None path. You need to return the value that the recursive call returns:

    else:
        return self.b(current.next, data)

BTW: using recursion for iterative programs like this is not a good idea in Python. Use iteration instead. Also, you have no clear termination condition.