Programs & Examples On #Microcontroller

This tag is related to questions that have something to do with a microcontroller. A microcontroller is a simple or small processor often with its program and execution memory on the same chip with input/output pins for controlling other hardware. Please specify the microcontroller and compiler or tools related to your question.

What is the difference between baud rate and bit rate?

I don't understand why everyone is making this complicated (answers).

I'll just leave this here.

bit rate vs. baud rate

So above would be:

  • Signal Unit: 4 bits
  • Baud Rate [Signal Units per second]: 1000 Bd (baud)
  • Bit Rate [Baud Rate * Signal Unit]: 4000 bps (bits per second)

Bit rate and Baud rate, these two terms are often used in data communication. Bit rate is simply the number of bits (i.e., 0’s and 1’s) transmitted per unit time. While Baud rate is the number of signal units transmitted per unit time that is needed to represent those bits.

How do I change TextView Value inside Java Code?

I presume that this question is a continuation of this one.

What are you trying to do? Do you really want to dynamically change the text in your TextView objects when the user clicks a button? You can certainly do that, if you have a reason, but, if the text is static, it is usually set in the main.xml file, like this:

<TextView  
android:id="@+id/rate"
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:text="@string/rate"
/>

The string "@string/rate" refers to an entry in your strings.xml file that looks like this:

<string name="rate">Rate</string>

If you really want to change this text later, you can do so by using Nikolay's example - you'd get a reference to the TextView by utilizing the id defined for it within main.xml, like this:


final TextView textViewToChange = (TextView) findViewById(R.id.rate);
textViewToChange.setText(
    "The new text that I'd like to display now that the user has pushed a button.");

MySQL error - #1932 - Table 'phpmyadmin.pma user config' doesn't exist in engine

I had the same error and it occured when changing the mysql/data folder to another folder.
I just copied all folders inside mysql/data folder to a new location except for two files. Those are ib_logfile0 and ib_logfile1; those are automatically created when starting the MySQL server. That worked for me.

how to parse json using groovy

That response is a Map, with a single element with key '212315952136472'. There's no 'data' key in the Map. If you want to loop through all entries, use something like this:

JSONObject userJson = JSON.parse(jsonResponse)
userJson.each { id, data -> println data.link }

If you know it's a single-element Map then you can directly access the link:

def data = userJson.values().iterator().next()
String link = data.link

And if you knew the id (e.g. if you used it to make the request) then you can access the value more concisely:

String id = '212315952136472'
...
String link = userJson[id].link

How to pass List from Controller to View in MVC 3

Passing data to view is simple as passing object to method. Take a look at Controller.View Method

protected internal ViewResult View(
    Object model
)

Something like this

//controller

List<MyObject> list = new List<MyObject>();

return View(list);


//view

@model List<MyObject>

// and property Model is type of List<MyObject>

@foreach(var item in Model)
{
    <span>@item.Name</span>
}

How to change fontFamily of TextView in Android

<string name="font_family_display_4_material">sans-serif-light</string>
<string name="font_family_display_3_material">sans-serif</string>
<string name="font_family_display_2_material">sans-serif</string>
<string name="font_family_display_1_material">sans-serif</string>
<string name="font_family_headline_material">sans-serif</string>
<string name="font_family_title_material">sans-serif-medium</string>
<string name="font_family_subhead_material">sans-serif</string>
<string name="font_family_menu_material">sans-serif</string>
<string name="font_family_body_2_material">sans-serif-medium</string>
<string name="font_family_body_1_material">sans-serif</string>
<string name="font_family_caption_material">sans-serif</string>
<string name="font_family_button_material">sans-serif-medium</string>

Integer ASCII value to character in BASH using printf

For your second question, it seems the leading-quote syntax (\'A) is specific to printf:

If the leading character is a single-quote or double-quote, the value shall be the numeric value in the underlying codeset of the character following the single-quote or double-quote.

From https://pubs.opengroup.org/onlinepubs/9699919799/utilities/printf.html

Getting char from string at specified index

Getting one char from string at specified index

Dim pos As Integer
Dim outStr As String
pos = 2 
Dim outStr As String
outStr = Left(Mid("abcdef", pos), 1)

outStr="b"

React ignores 'for' attribute of the label element

The for attribute is called htmlFor for consistency with the DOM property API. If you're using the development build of React, you should have seen a warning in your console about this.

How to execute python file in linux

1.save your file name as hey.py with the below given hello world script

#! /usr/bin/python
print('Hello, world!')

2.open the terminal in that directory

$ python hey.py

or if you are using python3 then

$ python3 hey.py

Best equivalent VisualStudio IDE for Mac to program .NET/C#

Whilst more of a workaround, if you're running an Intel Mac, you could go the virtualisation route - at least then you can run the same tools.

Table column sizing

I hacked this out for release Bootstrap 4.1.1 per my needs before I saw @florian_korner's post. Looks very similar.

If you use sass you can paste this snippet at the end of your bootstrap includes. It seems to fix the issue for chrome, IE, and edge. Does not seem to break anything in firefox.

@mixin make-td-col($size, $columns: $grid-columns) {
    width: percentage($size / $columns);
}

@each $breakpoint in map-keys($grid-breakpoints) {
    $infix: breakpoint-infix($breakpoint, $grid-breakpoints);

    @for $i from 1 through $grid-columns {
        td.col#{$infix}-#{$i}, th.col#{$infix}-#{$i} {
            @include make-td-col($i, $grid-columns);
        }
    }
}

or if you just want the compiled css utility:

td.col-1, th.col-1 {
  width: 8.33333%; }

td.col-2, th.col-2 {
  width: 16.66667%; }

td.col-3, th.col-3 {
  width: 25%; }

td.col-4, th.col-4 {
  width: 33.33333%; }

td.col-5, th.col-5 {
  width: 41.66667%; }

td.col-6, th.col-6 {
  width: 50%; }

td.col-7, th.col-7 {
  width: 58.33333%; }

td.col-8, th.col-8 {
  width: 66.66667%; }

td.col-9, th.col-9 {
  width: 75%; }

td.col-10, th.col-10 {
  width: 83.33333%; }

td.col-11, th.col-11 {
  width: 91.66667%; }

td.col-12, th.col-12 {
  width: 100%; }

td.col-sm-1, th.col-sm-1 {
  width: 8.33333%; }

td.col-sm-2, th.col-sm-2 {
  width: 16.66667%; }

td.col-sm-3, th.col-sm-3 {
  width: 25%; }

td.col-sm-4, th.col-sm-4 {
  width: 33.33333%; }

td.col-sm-5, th.col-sm-5 {
  width: 41.66667%; }

td.col-sm-6, th.col-sm-6 {
  width: 50%; }

td.col-sm-7, th.col-sm-7 {
  width: 58.33333%; }

td.col-sm-8, th.col-sm-8 {
  width: 66.66667%; }

td.col-sm-9, th.col-sm-9 {
  width: 75%; }

td.col-sm-10, th.col-sm-10 {
  width: 83.33333%; }

td.col-sm-11, th.col-sm-11 {
  width: 91.66667%; }

td.col-sm-12, th.col-sm-12 {
  width: 100%; }

td.col-md-1, th.col-md-1 {
  width: 8.33333%; }

td.col-md-2, th.col-md-2 {
  width: 16.66667%; }

td.col-md-3, th.col-md-3 {
  width: 25%; }

td.col-md-4, th.col-md-4 {
  width: 33.33333%; }

td.col-md-5, th.col-md-5 {
  width: 41.66667%; }

td.col-md-6, th.col-md-6 {
  width: 50%; }

td.col-md-7, th.col-md-7 {
  width: 58.33333%; }

td.col-md-8, th.col-md-8 {
  width: 66.66667%; }

td.col-md-9, th.col-md-9 {
  width: 75%; }

td.col-md-10, th.col-md-10 {
  width: 83.33333%; }

td.col-md-11, th.col-md-11 {
  width: 91.66667%; }

td.col-md-12, th.col-md-12 {
  width: 100%; }

td.col-lg-1, th.col-lg-1 {
  width: 8.33333%; }

td.col-lg-2, th.col-lg-2 {
  width: 16.66667%; }

td.col-lg-3, th.col-lg-3 {
  width: 25%; }

td.col-lg-4, th.col-lg-4 {
  width: 33.33333%; }

td.col-lg-5, th.col-lg-5 {
  width: 41.66667%; }

td.col-lg-6, th.col-lg-6 {
  width: 50%; }

td.col-lg-7, th.col-lg-7 {
  width: 58.33333%; }

td.col-lg-8, th.col-lg-8 {
  width: 66.66667%; }

td.col-lg-9, th.col-lg-9 {
  width: 75%; }

td.col-lg-10, th.col-lg-10 {
  width: 83.33333%; }

td.col-lg-11, th.col-lg-11 {
  width: 91.66667%; }

td.col-lg-12, th.col-lg-12 {
  width: 100%; }

td.col-xl-1, th.col-xl-1 {
  width: 8.33333%; }

td.col-xl-2, th.col-xl-2 {
  width: 16.66667%; }

td.col-xl-3, th.col-xl-3 {
  width: 25%; }

td.col-xl-4, th.col-xl-4 {
  width: 33.33333%; }

td.col-xl-5, th.col-xl-5 {
  width: 41.66667%; }

td.col-xl-6, th.col-xl-6 {
  width: 50%; }

td.col-xl-7, th.col-xl-7 {
  width: 58.33333%; }

td.col-xl-8, th.col-xl-8 {
  width: 66.66667%; }

td.col-xl-9, th.col-xl-9 {
  width: 75%; }

td.col-xl-10, th.col-xl-10 {
  width: 83.33333%; }

td.col-xl-11, th.col-xl-11 {
  width: 91.66667%; }

td.col-xl-12, th.col-xl-12 {
  width: 100%; }

PHP array delete by value (not key)

If you don't know its key it means it doesn't matter.

You could place the value as the key, it means it will instantly find the value. Better than using searching in all elements over and over again.

$messages=array();   
$messages[312] = 312;    
$messages[401] = 401;   
$messages[1599] = 1599;   
$messages[3] = 3;    

unset($messages[3]); // no search needed

Install dependencies globally and locally using package.json

Due to the disadvantages described below, I would recommend following the accepted answer:

Use npm install --save-dev [package_name] then execute scripts with:

$ npm run lint
$ npm run build
$ npm test

My original but not recommended answer follows.


Instead of using a global install, you could add the package to your devDependencies (--save-dev) and then run the binary from anywhere inside your project:

"$(npm bin)/<executable_name>" <arguments>...

In your case:

"$(npm bin)"/node.io --help

This engineer provided an npm-exec alias as a shortcut. This engineer uses a shellscript called env.sh. But I prefer to use $(npm bin) directly, to avoid any extra file or setup.

Although it makes each call a little larger, it should just work, preventing:

  • potential dependency conflicts with global packages (@nalply)
  • the need for sudo
  • the need to set up an npm prefix (although I recommend using one anyway)

Disadvantages:

  • $(npm bin) won't work on Windows.
  • Tools deeper in your dev tree will not appear in the npm bin folder. (Install npm-run or npm-which to find them.)

It seems a better solution is to place common tasks (such as building and minifying) in the "scripts" section of your package.json, as Jason demonstrates above.

How to read files and stdout from a running Docker container

To view the stdout, you can start the docker container with -i. This of course does not enable you to leave the started process and explore the container.

docker start -i containerid

Alternatively you can view the filesystem of the container at

/var/lib/docker/containers/containerid/root/

However neither of these are ideal. If you want to view logs or any persistent storage, the correct way to do so would be attaching a volume with the -v switch when you use docker run. This would mean you can inspect log files either on the host or attach them to another container and inspect them there.

What is SOA "in plain english"?

from ittoolbox blogs.

The following outlines the similarities and differences to past design techniques:

• SOA versus Structured Programming o Similarities: Most similar to subroutine calls where parameters are passed and the operation of the function is abstracted from the caller - e.g. CICS link and execute and the COBOL CALL reserved word. Copybooks are used to define data structure which is typically defined as an XML schema for services. o Differences: SOA is loosely coupled implying changes to a service have less impact to the consumer (the "calling" program) and services are interoperable across languages and platforms.

• SOA versus OOA/OOD o Similarities: Encapsulation, Abstraction and Defined Interfaces o Differences: SOA is loosely coupled with no class hierarchy or inheritance, Low-level abstractions - class level versus business service

• SOA versus legacy Component Based Development (CBD) - e.g. CORBA, DCOM, EJB o Similarities: Reuse through assembling components, Interfaces, Remote calls o Differences: Wide adoption of standards, XML Schemas vs. Marshaled Objects, Service Orchestration, Designing for reuse is easier, services are business focused vs. IT focused, business services are course grained (broad in scope)

• SOA (for integration) versus Enterprise Application Integration (EAI) o Similarities: Best practices (well defined interfaces, standardized schemas, event driven architecture), reusable interfaces, common schemas o Differences: Standards, adoption, and improved tools

How to add a spinner icon to button when it's in the Loading state?

If you look at the bootstrap-button.js source, you'll see that the bootstrap plugin replaces the buttons inner html with whatever is in data-loading-text when calling $(myElem).button('loading').

For your case, I think you should just be able to do this:

<button type="button"
        class="btn btn-primary start"
        id="btnStartUploads"
        data-loading-text="<i class='icon-spinner icon-spin icon-large'></i> @Localization.Uploading">
    <i class="icon-upload icon-large"></i>
    <span>@Localization.StartUpload</span>
</button>

Running Facebook application on localhost

In my case the issue revealed to be chrome blocking the CORS request from localhost:4200 to facebook api website. Running Chrome with this setting: "YOUR_PATH_TO_CHROME\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="c:/chrome worked like a charm while developing. Even with no localhost added to facebook app's settings.

How can I send large messages with Kafka (over 15MB)?

You need to override the following properties:

Broker Configs($KAFKA_HOME/config/server.properties)

  • replica.fetch.max.bytes
  • message.max.bytes

Consumer Configs($KAFKA_HOME/config/consumer.properties)
This step didn't work for me. I add it to the consumer app and it was working fine

  • fetch.message.max.bytes

Restart the server.

look at this documentation for more info: http://kafka.apache.org/08/configuration.html

Sorting a vector of custom objects

I was curious if there is any measurable impact on performance between the various ways one can call std::sort, so I've created this simple test:

$ cat sort.cpp
#include<algorithm>
#include<iostream>
#include<vector>
#include<chrono>

#define COMPILER_BARRIER() asm volatile("" ::: "memory");

typedef unsigned long int ulint;

using namespace std;

struct S {
  int x;
  int y;
};

#define BODY { return s1.x*s2.y < s2.x*s1.y; }

bool operator<( const S& s1, const S& s2 ) BODY
bool Sgreater_func( const S& s1, const S& s2 ) BODY

struct Sgreater {
  bool operator()( const S& s1, const S& s2 ) const BODY
};

void sort_by_operator(vector<S> & v){
  sort(v.begin(), v.end());
}

void sort_by_lambda(vector<S> & v){
  sort(v.begin(), v.end(), []( const S& s1, const S& s2 ) BODY );
}

void sort_by_functor(vector<S> &v){
  sort(v.begin(), v.end(), Sgreater());
}

void sort_by_function(vector<S> &v){
  sort(v.begin(), v.end(), &Sgreater_func);
}

const int N = 10000000;
vector<S> random_vector;

ulint run(void foo(vector<S> &v)){
  vector<S> tmp(random_vector);
  foo(tmp);
  ulint checksum = 0;
  for(int i=0;i<tmp.size();++i){
     checksum += i *tmp[i].x ^ tmp[i].y;
  }
  return checksum;
}

void measure(void foo(vector<S> & v)){

ulint check_sum = 0;

  // warm up
  const int WARMUP_ROUNDS = 3;
  const int TEST_ROUNDS = 10;

  for(int t=WARMUP_ROUNDS;t--;){
    COMPILER_BARRIER();
    check_sum += run(foo);
    COMPILER_BARRIER();
  }

  for(int t=TEST_ROUNDS;t--;){
    COMPILER_BARRIER();
    auto start = std::chrono::high_resolution_clock::now();
    COMPILER_BARRIER();
    check_sum += run(foo);
    COMPILER_BARRIER();
    auto end = std::chrono::high_resolution_clock::now();
    COMPILER_BARRIER();
    auto duration_ns = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count();

    cout << "Took " << duration_ns << "s to complete round" << endl;
  }

  cout << "Checksum: " << check_sum << endl;
}

#define M(x) \
  cout << "Measure " #x " on " << N << " items:" << endl;\
  measure(x);

int main(){
  random_vector.reserve(N);

  for(int i=0;i<N;++i){
    random_vector.push_back(S{rand(), rand()});
  }

  M(sort_by_operator);
  M(sort_by_lambda);
  M(sort_by_functor);
  M(sort_by_function);
  return 0;
}

What it does is it creates a random vector, and then measures how much time is required to copy it and sort the copy of it (and compute some checksum to avoid too vigorous dead code elimination).

I was compiling with g++ (GCC) 7.2.1 20170829 (Red Hat 7.2.1-1)

$ g++ -O2 -o sort sort.cpp && ./sort

Here are results:

Measure sort_by_operator on 10000000 items:
Took 0.994285s to complete round
Took 0.990162s to complete round
Took 0.992103s to complete round
Took 0.989638s to complete round
Took 0.98105s to complete round
Took 0.991913s to complete round
Took 0.992176s to complete round
Took 0.981706s to complete round
Took 0.99021s to complete round
Took 0.988841s to complete round
Checksum: 18446656212269526361
Measure sort_by_lambda on 10000000 items:
Took 0.974274s to complete round
Took 0.97298s to complete round
Took 0.964506s to complete round
Took 0.96899s to complete round
Took 0.965773s to complete round
Took 0.96457s to complete round
Took 0.974286s to complete round
Took 0.975524s to complete round
Took 0.966238s to complete round
Took 0.964676s to complete round
Checksum: 18446656212269526361
Measure sort_by_functor on 10000000 items:
Took 0.964359s to complete round
Took 0.979619s to complete round
Took 0.974027s to complete round
Took 0.964671s to complete round
Took 0.964764s to complete round
Took 0.966491s to complete round
Took 0.964706s to complete round
Took 0.965115s to complete round
Took 0.964352s to complete round
Took 0.968954s to complete round
Checksum: 18446656212269526361
Measure sort_by_function on 10000000 items:
Took 1.29942s to complete round
Took 1.3029s to complete round
Took 1.29931s to complete round
Took 1.29946s to complete round
Took 1.29837s to complete round
Took 1.30132s to complete round
Took 1.3023s to complete round
Took 1.30997s to complete round
Took 1.30819s to complete round
Took 1.3003s to complete round
Checksum: 18446656212269526361

Looks like all the options except for passing function pointer are very similar, and passing a function pointer causes +30% penalty.

It also looks like the operator< version is ~1% slower (I repeated the test multiple times and the effect persists), which is a bit strange as it suggests that the generated code is different (I lack skill to analyze --save-temps output).

Quickest way to clear all sheet contents VBA

You can use the .Clear method:

Sheets("Zeros").UsedRange.Clear

Using this you can remove the contents and the formatting of a cell or range without affecting the rest of the worksheet.

How to do "If Clicked Else .."

 var flag = 0;

 $('#target').click(function() {
    flag = 1;
 });

 if (flag == 1)
 {
  alert("Clicked");
 }
 else
 {
   alert("Not clicked");
 }

How to create a link to a directory

you should use :

ln -s /home/jake/doc/test/2000/something xxx

Oracle PL/SQL string compare issue

Only change the line str1:=''; to str1:=' ';

Get root view from current activity

if you are in a activity, assume there is only one root view,you can get it like this.

ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this
        .findViewById(android.R.id.content)).getChildAt(0);

you can then cast it to your real class

or you could using

getWindow().getDecorView();

notice this will include the actionbar view, your view is below the actionbar view

Appending to 2D lists in Python

Came here to see how to append an item to a 2D array, but the title of the thread is a bit misleading because it is exploring an issue with the appending.

The easiest way I found to append to a 2D list is like this:

list=[[]]

list.append((var_1,var_2))

This will result in an entry with the 2 variables var_1, var_2. Hope this helps!

How to resolve the error on 'react-native start'

As a general rule, I don't modify files within node_modules/ (or anything which does not get committed as part of a repository) as the next clean, build or update will regress them. I definitely have done so in the past and it has bitten me a couple of times. But this does work as a short-term/local dev fix until/unless metro-config is updated.

Thanks!

Using port number in Windows host file

You need NGNIX or Apache HTTP server as a proxy server for forwarding http requests to appropriate application -> which listens particular port (or do it with CNAME which provides Hosting company). It is most powerful solution and this is just a really easy way to keep adding new subdomains, or to add new domains automatically when DNS records are pointed at the server.

Java 8 method references: provide a Supplier capable of supplying a parameterized result

It appears that you can throw only RuntimeException from the method orElseThrow. Otherwise you will get an error message like MyException cannot be converted to java.lang.RuntimeException

Update:- This was an issue with an older version of JDK. I don't see this issue with the latest versions.

Use of #pragma in C

#pragma is used to do something implementation-specific in C, i.e. be pragmatic for the current context rather than ideologically dogmatic.

The one I regularly use is #pragma pack(1) where I'm trying to squeeze more out of my memory space on embedded solutions, with arrays of structures that would otherwise end up with 8 byte alignment.

Pity we don't have a #dogma yet. That would be fun ;)

How do I completely rename an Xcode project (i.e. inclusive of folders)?

There is a GitHub project called Xcode Project Renamer:

It should be executed from inside root of Xcode project directory and called with two string parameters: $OLD_PROJECT_NAME & $NEW_PROJECT_NAME

Script goes through all the files and directories recursively, including Xcode project or workspace file and replaces all occurrences of $OLD_PROJECT_NAME string with $NEW_PROJECT_NAME string (both in each file's name and content).

DON'T FORGET TO BACKUP YOUR PROJECT!

Xcode Project Renamer

Is it possible to use if...else... statement in React render function?

There actually is a way to do exactly what OP is asking. Just render and call an anonymous function like so:

render () {
  return (
    <div>
      {(() => {
        if (someCase) {
          return (
            <div>someCase</div>
          )
        } else if (otherCase) {
          return (
            <div>otherCase</div>
          )
        } else {
          return (
            <div>catch all</div>
          )
        }
      })()}
    </div>
  )
}

Retrofit and GET using parameters

@QueryMap worked for me instead of FieldMap

If you have a bunch of GET params, another way to pass them into your url is a HashMap.

class YourActivity extends Activity {

private static final String BASEPATH = "http://www.example.com";

private interface API {
    @GET("/thing")
    void getMyThing(@QueryMap Map<String, String> params, new Callback<String> callback);
}

public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.your_layout);

   RestAdapter rest = new RestAdapter.Builder().setEndpoint(BASEPATH).build();
   API service = rest.create(API.class);

   Map<String, String> params = new HashMap<String, String>();
   params.put("key1", "val1");
   params.put("key2", "val2");
   // ... as much as you need.

   service.getMyThing(params, new Callback<String>() {
       // ... do some stuff here.
   });
}
}

The URL called will be http://www.example.com/thing/?key1=val1&key2=val2

Set object property using reflection

You can also access fields using a simillar manner:

var obj=new MyObject();
FieldInfo fi = obj.GetType().
  GetField("Name", BindingFlags.NonPublic | BindingFlags.Instance);
fi.SetValue(obj,value)

With reflection everything can be an open book:) In my example we are binding to a private instance level field.

MySQL - UPDATE query with LIMIT

You should use IS rather than = for comparing to NULL.

UPDATE `smartmeter_usage`.`users_reporting`
SET panel_id = 3
WHERE panel_id IS null

The LIMIT clause in MySQL when applied to an update does not permit an offset to be specified.

Paste Excel range in Outlook

Often this question is asked in the context of Ron de Bruin's RangeToHTML function, which creates an HTML PublishObject from an Excel.Range, extracts that via FSO, and inserts the resulting stream HTML in to the email's HTMLBody. In doing so, this removes the default signature (the RangeToHTML function has a helper function GetBoiler which attempts to insert the default signature).

Unfortunately, the poorly-documented Application.CommandBars method is not available via Outlook:

wdDoc.Application.CommandBars.ExecuteMso "PasteExcelTableSourceFormatting"

It will raise a runtime 6158:

enter image description here

But we can still leverage the Word.Document which is accessible via the MailItem.GetInspector method, we can do something like this to copy & paste the selection from Excel to the Outlook email body, preserving your default signature (if there is one).

Dim rng as Range
Set rng = Range("A1:F10") 'Modify as needed

With OutMail
    .To = "[email protected]"
    .BCC = ""
    .Subject = "Subject"
    .Display
    Dim wdDoc As Object     '## Word.Document
    Dim wdRange As Object   '## Word.Range
    Set wdDoc = OutMail.GetInspector.WordEditor
    Set wdRange = wdDoc.Range(0, 0)
    wdRange.InsertAfter vbCrLf & vbCrLf
    'Copy the range in-place
    rng.Copy
    wdRange.Paste
End With

Note that in some cases this may not perfectly preserve the column widths or in some instances the row heights, and while it will also copy shapes and other objects in the Excel range, this may also cause some funky alignment issues, but for simple tables and Excel ranges, it is very good:

enter image description here

HTML table with horizontal scrolling (first column fixed)

Based on skube's approach, I found the minimal set of CSS I needed was:

_x000D_
_x000D_
.horizontal-scroll-except-first-column {_x000D_
  width: 100%;_x000D_
  overflow: auto;_x000D_
}_x000D_
_x000D_
.horizontal-scroll-except-first-column > table {_x000D_
  margin-left: 8em;_x000D_
}_x000D_
_x000D_
.horizontal-scroll-except-first-column > table > * > tr > th:first-child,_x000D_
.horizontal-scroll-except-first-column > table > * > tr > td:first-child {_x000D_
  position: absolute;_x000D_
  width: 8em;_x000D_
  margin-left: -8em;_x000D_
  background: #ccc;_x000D_
}_x000D_
_x000D_
.horizontal-scroll-except-first-column > table > * > tr > th,_x000D_
.horizontal-scroll-except-first-column > table > * > tr > td {_x000D_
  /* Without this, if a cell wraps onto two lines, the first column_x000D_
   * will look bad, and may need padding. */_x000D_
  white-space: nowrap;_x000D_
}
_x000D_
<div class="horizontal-scroll-except-first-column">_x000D_
  <table>_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <td>FIXED</td> <td>22222</td> <td>33333</td> <td>44444</td> <td>55555</td> <td>66666</td> <td>77777</td> <td>88888</td> <td>99999</td> <td>AAAAA</td> <td>BBBBB</td> <td>CCCCC</td> <td>DDDDD</td> <td>EEEEE</td> <td>FFFFF</td>_x000D_
      </tr>_x000D_
    </tbody>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I convert an object to an array?

Careful:

$array = (array) $object;

does a shallow conversion ($object->innerObject = new stdClass() remains an object) and converting back and forth using json works but it's not a good idea if performance is an issue.

If you need all objects to be converted to associative arrays here is a better way to do that (code ripped from I don't remember where):

function toArray($obj)
{
    if (is_object($obj)) $obj = (array)$obj;
    if (is_array($obj)) {
        $new = array();
        foreach ($obj as $key => $val) {
            $new[$key] = toArray($val);
        }
    } else {
        $new = $obj;
    }

    return $new;
}

Do you use NULL or 0 (zero) for pointers in C++?

I think the standard guarantees that NULL == 0, so you can do either. I prefer NULL because it documents your intent.

Wrapping long text without white space inside of a div

white-space: pre-wrap

is what worked for me for <span> and <div>.

Prevent screen rotation on Android

The easiest way I found to do this was to put

this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

within onCreate, just after

setContentView(R.layout.activity_main);

so...

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

How to Programmatically Add Views to Views

for anyone yet interested:

the best way I found is to use the inflate static method of View.

View inflatedView = View.inflate(context, yourViewXML, yourLinearLayout);

where yourViewXML is something like R.layout.myView

please notice that you need a ViewGroup in order to add a view (which is any layout you can think of)

so as an example lets say you have a fragment which it view already been inflated and you know that the root view is a layout, and you want to add a view to it:

    View view = getView(); // returns base view of the fragment
    if (view == null)
        return;
    if (!(view instanceof ViewGroup))
        return;

    ViewGroup viewGroup = (ViewGroup) view;
    View popup = View.inflate(viewGroup.getContext(), R.layout.someView, viewGroup);

Comparing date part only without comparing time in JavaScript

Using Moment.js

If you have the option of including a third-party library, it's definitely worth taking a look at Moment.js. It makes working with Date and DateTime much, much easier.

For example, seeing if one Date comes after another Date but excluding their times, you would do something like this:

var date1 = new Date(2016,9,20,12,0,0); // October 20, 2016 12:00:00
var date2 = new Date(2016,9,20,12,1,0); // October 20, 2016 12:01:00

// Comparison including time.
moment(date2).isAfter(date1); // => true

// Comparison excluding time.
moment(date2).isAfter(date1, 'day'); // => false

The second parameter you pass into isAfter is the precision to do the comparison and can be any of year, month, week, day, hour, minute or second.

How to bring view in front of everything?

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

Python def function: How do you specify the end of the function?

In Python whitespace is significant. The function ends when the indentation becomes smaller (less).

def f():
    pass # first line
    pass # second line
pass # <-- less indentation, not part of function f.

Note that one-line functions can be written without indentation, on one line:

def f(): pass

And, then there is the use of semi-colons, but this is not recommended:

def f(): pass; pass

The three forms above show how the end of a function is defined syntactically. As for the semantics, in Python there are three ways to exit a function:

  • Using the return statement. This works the same as in any other imperative programming language you may know.

  • Using the yield statement. This means that the function is a generator. Explaining its semantics is beyond the scope of this answer. Have a look at Can somebody explain me the python yield statement?

  • By simply executing the last statement. If there are no more statements and the last statement is not a return statement, then the function exists as if the last statement were return None. That is to say, without an explicit return statement a function returns None. This function returns None:

    def f():
        pass
    

    And so does this one:

    def f():
        42
    

MongoDB - admin user not authorized

For MongoDB shell version v4.2.8 I've tried different ways to back-up my database with auth, my winner solution is

mongodump -h <your_hostname> -d <your_db_name> -u <your_db_username> -p <your_db_password> --authenticationDatabase admin -o /path/to/where/i/want

Could not create work tree dir 'example.com'.: Permission denied

Turns out the problem was in the permission. I fix it with the following command

sudo chown -R $USER /var/www

Please make sure with the $USER variable. I tested and worked on Ubuntu Distro

Datetime format Issue: String was not recognized as a valid DateTime

try this:

string strTime = "04/30/2013 23:00";
DateTime dtTime;
if(DateTime.TryParseExact(strTime, "MM/dd/yyyy HH:mm",  
   System.Globalization.CultureInfo.InvariantCulture, 
   System.Globalization.DateTimeStyles.None, out dtTime))
 {
    Console.WriteLine(dtTime);
 }

jQuery checkbox checked state changed event

Try this jQuery validation

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#myform').validate({ // initialize the plugin_x000D_
    rules: {_x000D_
      agree: {_x000D_
        required: true_x000D_
      }_x000D_
_x000D_
    },_x000D_
    submitHandler: function(form) {_x000D_
      alert('valid form submitted');_x000D_
      return false;_x000D_
    }_x000D_
  });_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>_x000D_
_x000D_
<form id="myform" action="" method="post">_x000D_
  <div class="buttons">_x000D_
    <div class="pull-right">_x000D_
      <input type="checkbox" name="agree" /><br/>_x000D_
      <label>I have read and agree to the <a href="https://stackexchange.com/legal/terms-of-service">Terms of services</a> </label>_x000D_
    </div>_x000D_
  </div>_x000D_
  <button type="submit">Agree</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

What are the differences between numpy arrays and matrices? Which one should I use?

Just to add one case to unutbu's list.

One of the biggest practical differences for me of numpy ndarrays compared to numpy matrices or matrix languages like matlab, is that the dimension is not preserved in reduce operations. Matrices are always 2d, while the mean of an array, for example, has one dimension less.

For example demean rows of a matrix or array:

with matrix

>>> m = np.mat([[1,2],[2,3]])
>>> m
matrix([[1, 2],
        [2, 3]])
>>> mm = m.mean(1)
>>> mm
matrix([[ 1.5],
        [ 2.5]])
>>> mm.shape
(2, 1)
>>> m - mm
matrix([[-0.5,  0.5],
        [-0.5,  0.5]])

with array

>>> a = np.array([[1,2],[2,3]])
>>> a
array([[1, 2],
       [2, 3]])
>>> am = a.mean(1)
>>> am.shape
(2,)
>>> am
array([ 1.5,  2.5])
>>> a - am #wrong
array([[-0.5, -0.5],
       [ 0.5,  0.5]])
>>> a - am[:, np.newaxis]  #right
array([[-0.5,  0.5],
       [-0.5,  0.5]])

I also think that mixing arrays and matrices gives rise to many "happy" debugging hours. However, scipy.sparse matrices are always matrices in terms of operators like multiplication.

Can Windows Containers be hosted on linux?

Containers use the OS kernel. Windows Container utilize processes in order to run. So theoretically speaking Windows Containers cannot run on Linux.

However there are workarounds utilizing VMstyle solutions.

I Have found this solution which uses Vagrant and Packer on Mac, so it should work for Linux as well: https://github.com/StefanScherer/windows-docker-machine

This Vagrant environment creates a Docker Machine to work on your MacBook with Windows containers. You can easily switch between Docker for Mac Linux containers and the Windows containers.

Running bash commands enter image description here

building the headless Vagrant box

$ git clone https://github.com/StefanScherer/packer-windows
$ cd packer-windows

$ packer build --only=vmware-iso windows_2019_docker.json
$ vagrant box add windows_2019_docker windows_2019_docker_vmware.box

Create the Docker Machine

$ git clone https://github.com/StefanScherer/windows-docker-machine
$ cd windows-docker-machine
$ vagrant up --provider vmware_fusion 2019

Switch to Windows containers

$ eval $(docker-machine env 2019)

How to test an SQL Update statement before running it?

What about Transactions? They have the ROLLBACK-Feature.

@see https://dev.mysql.com/doc/refman/5.0/en/commit.html

For example:

START TRANSACTION;
SELECT * FROM nicetable WHERE somthing=1;
UPDATE nicetable SET nicefield='VALUE' WHERE somthing=1;
SELECT * FROM nicetable WHERE somthing=1; #check

COMMIT;
# or if you want to reset changes 
ROLLBACK;

SELECT * FROM nicetable WHERE somthing=1; #should be the old value

Answer on question from @rickozoe below:

In general these lines will not be executed as once. In PHP f.e. you would write something like that (perhaps a little bit cleaner, but wanted to answer quick ;-) ):

$MysqlConnection->query('START TRANSACTION;');
$erg = $MysqlConnection->query('UPDATE MyGuests SET lastname='Doe' WHERE id=2;');
if($erg)
    $MysqlConnection->query('COMMIT;');
else
    $MysqlConnection->query('ROLLBACK;');

Another way would be to use MySQL Variables (see https://dev.mysql.com/doc/refman/5.7/en/user-variables.html and https://stackoverflow.com/a/18499823/1416909 ):

# do some stuff that should be conditionally rollbacked later on

SET @v1 := UPDATE MyGuests SET lastname='Doe' WHERE id=2;
IF(v1 < 1) THEN
    ROLLBACK;
ELSE
    COMMIT;
END IF;

But I would suggest to use the language wrappers available in your favorite programming language.

Blurry text after using CSS transform: scale(); in Chrome

This must be a bug with Chrome (Version 56.0.2924.87), but the below fixes the bluriness for me when changing css properties in the console('.0'). I'll report it.

filter: blur(.0px)

What is the difference between AF_INET and PF_INET in socket programming?

I found in Linux kernel source code that PF_INET and AF_INET are the same. The following code is from file include/linux/socket.h, line 204 of Linux kernel 3.2.21 tree.

/* Protocol families, same as address families. */
...
#define PF_INET     AF_INET

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

If you don't care about the number of occurrences, I would approach it like this. Using hash sets will give you better performance than simple iteration.

var set1 = new HashSet<MyType>(list1);
var set2 = new HashSet<MyType>(list2);
return set1.SetEquals(set2);

This will require that you have overridden .GetHashCode() and implemented IEquatable<MyType> on MyType.

Convert a JSON string to object in Java ME?

You can do this easily with Google GSON.

Let's say you have a class called User with the fields user, width, and height and you want to convert the following json string to the User object.

{"name":"MyNode", "width":200, "height":100}

You can easily do so, without having to cast (keeping nimcap's comment in mind ;) ), with the following code:

Gson gson = new Gson(); 
final User user = gson.fromJson(jsonString, User.class);

Where jsonString is the above JSON String.

For more information, please look into https://code.google.com/p/google-gson/

How to check if a char is equal to an empty space?

The code you needs depends on what you mean by "an empty space".

  • If you mean the ASCII / Latin-1 / Unicode space character (0x20) aka SP, then:

    if (ch == ' ') {
        // ...
    }
    
  • If you mean any of the traditional ASCII whitespace characters (SP, HT, VT, CR, NL), then:

    if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '\x0b') {
        // ...
    }
    
  • If you mean any Unicode whitespace character, then:

    if (Character.isWhitespace(ch)) {
        // ...
    }
    

Note that there are Unicode whitespace includes additional ASCII control codes, and some other Unicode characters in higher code planes; see the javadoc for Character.isWhitespace(char).


What you wrote was this:

    if (Equals(ch, " ")) {
        // ...
    }

This is wrong on a number of levels. Firstly, the way that the Java compiler tries to interpret that is as a call to a method with a signature of boolean Equals(char, String).

  • This is wrong because no method exists, as the compiler reported in the error message.
  • Equals wouldn't normally be the name of a method anyway. The Java convention is that method names start with a lower case letter.
  • Your code (as written) was trying to compare a character and a String, but char and String are not comparable and cannot be cast to a common base type.

There is such a thing as a Comparator in Java, but it is an interface not a method, and it is declared like this:

    public interface Comparator<T> {
        public int compare(T v1, T v2);
    }

In other words, the method name is compare (not Equals), it returns an integer (not a boolean), and it compares two values that can be promoted to the type given by the type parameter.


Someone (in a deleted Answer!) said they tried this:

    if (c == " ")

That fails for two reasons:

  • " " is a String literal and not a character literal, and Java does not allow direct comparison of String and char values.

  • You should NEVER compare Strings or String literals using ==. The == operator on a reference type compares object identity, not object value. In the case of String it is common to have different objects with different identity and the same value. An == test will often give the wrong answer ... from the perspective of what you are trying to do here.

Is there a goto statement in Java?

goto is not in Java

you have to use GOTO But it don't work correctly.in key java word it is not used. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html

   public static void main(String[] args) {            
            GOTO me;
            //code;
            me:
            //code; 
            }   
   }

Get the string within brackets in Python

your_string = "lnfgbdgfi343456dsfidf[my data] ljfbgns47647jfbgfjbgskj"
your_string[your_string.find("[")+1 : your_string.find("]")]

courtesy: Regular expression to return text between parenthesis

Why can't overriding methods throw exceptions broader than the overridden method?

The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method.

Example:

class Super {
    public void throwCheckedExceptionMethod() throws IOException {
        FileReader r = new FileReader(new File("aFile.txt"));
        r.close();
    }
}

class Sub extends Super {    
    @Override
    public void throwCheckedExceptionMethod() throws FileNotFoundException {
        // FileNotFoundException extends IOException
        FileReader r = new FileReader(new File("afile.txt"));
        try {
            // close() method throws IOException (that is unhandled)
            r.close();
        } catch (IOException e) {
        }
    }
}

class Sub2 extends Sub {
    @Override
    public void throwCheckedExceptionMethod() {
        // Overriding method can throw no exception
    }
}

Python, how to check if a result set is empty?

Notice: This is for MySQLdb module in Python.

For a SELECT statement, there shouldn't be an exception for an empty recordset. Just an empty list ([]) for cursor.fetchall() and None for cursor.fetchone().

For any other statement, e.g. INSERT or UPDATE, that doesn't return a recordset, you can neither call fetchall() nor fetchone() on the cursor. Otherwise, an exception will be raised.

There's one way to distinguish between the above two types of cursors:

def yield_data(cursor):
    while True:
        if cursor.description is None:
            # No recordset for INSERT, UPDATE, CREATE, etc
            pass
        else:
            # Recordset for SELECT, yield data
            yield cursor.fetchall()
            # Or yield column names with
            # yield [col[0] for col in cursor.description]

        # Go to the next recordset
        if not cursor.nextset():
            # End of recordsets
            return

don't fail jenkins build if execute shell fails

To stop further execution when command fails:

command || exit 0

To continue execution when command fails:

command || true

How do I automatically set the $DISPLAY variable for my current session?

I'm guessing here, based on issues I've had in the past which I did solve:

  • you're connecting to a vnc server on machine B, displaying it using a VNC client on machine A
  • you're launching a console (xterm or equivalent) on machine B and using that to connect to machine C
  • you want to launch an X-based application on machine C, having it display to the VNC server on machine B, so you can see it on machine A.

I ended up with two solutions. My original solution was based on using rsh. Since then, most of our servers have had ssh installed, which has made this easier.

Using rsh, I put together a table of machines vs OS vs custom options which would guide this process in perl. Bourne shell wasn't sufficient, and we don't have bash on Sun or HP machines (and didn't have bash on AIX at the time - AIX 5L wasn't out yet). Korn shell wasn't much of an option, either, since most of our Linux boxes don't have pdksh installed. But, if you don't face these limitations, you can implement the idea in ksh or bash, I think.

Anyway, I would basically run 'rsh $machine -l $user "$cmd"' where $machine, of course, was the machine I was logging in to, $user, similarly obvious (though when I was going in as "root" this had some variance as we have multiple roots on some machines for reasons I don't fully understand), and $cmd was basically "DISPLAY=$DISPLAY xterm", though if I were launching konsole, for example, $cmd would be "konsole --display=$DISPLAY". Since $DISPLAY was being evaluated locally (where it's set properly), and not being passed literally across rsh, the display would always be set correctly.

I also had to make sure that no one did anything silly like reset DISPLAY if it was already set.

Now, I just use ssh, make sure that X11Forwarding is set to yes on the server (sshd_config), and then I can just ssh to the machine, let X commands go across the wire encrypted, and it'll always go back to the right place.

What's the @ in front of a string in C#?

Since you explicitly asked for VB as well, let me just add that this verbatim string syntax doesn't exist in VB, only in C#. Rather, all strings are verbatim in VB (except for the fact that they cannot contain line breaks, unlike C# verbatim strings):

Dim path = "C:\My\Path"
Dim message = "She said, ""Hello, beautiful world."""

Escape sequences don't exist in VB (except for the doubling of the quote character, like in C# verbatim strings) which makes a few things more complicated. For example, to write the following code in VB you need to use concatenation (or any of the other ways to construct a string)

string x = "Foo\nbar";

In VB this would be written as follows:

Dim x = "Foo" & Environment.NewLine & "bar"

(& is the VB string concatenation operator. + could equally be used.)

Python - Extracting and Saving Video Frames

To extend on this question (& answer by @user2700065) for a slightly different cases, if anyone does not want to extract every frame but wants to extract frame every one second. So a 1-minute video will give 60 frames(images).

import sys
import argparse

import cv2
print(cv2.__version__)

def extractImages(pathIn, pathOut):
    count = 0
    vidcap = cv2.VideoCapture(pathIn)
    success,image = vidcap.read()
    success = True
    while success:
        vidcap.set(cv2.CAP_PROP_POS_MSEC,(count*1000))    # added this line 
        success,image = vidcap.read()
        print ('Read a new frame: ', success)
        cv2.imwrite( pathOut + "\\frame%d.jpg" % count, image)     # save frame as JPEG file
        count = count + 1

if __name__=="__main__":
    a = argparse.ArgumentParser()
    a.add_argument("--pathIn", help="path to video")
    a.add_argument("--pathOut", help="path to images")
    args = a.parse_args()
    print(args)
    extractImages(args.pathIn, args.pathOut)

Android Studio build fails with "Task '' not found in root project 'MyProject'."

This happened to me recently when I close one Android Studio project and imported another Eclipse project. It seemed to be some bug in Android Studio where it preserves some gradle settings from previously open project and then get confused in the new project.

The solution was extremely simple: Close the project and shut down Android Studio completely, before re-opening it and then import/open the new project. Everything goes smoothly from then on.

Restart android machine

adb reboot should not reboot your linux box.

But in any case, you can redirect the command to a specific adb device using adb -s <device_id> command , where

Device ID can be obtained from the command adb devices
command in this case is reboot

What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

The difference is that if you only specify the DOCTYPE, IE’s Compatibility View Settings take precedence. By default these settings force all intranet sites into Compatibility View regardless of DOCTYPE. There’s also a checkbox to use Compatibility View for all websites, regardless of DOCTYPE.

IE Compatibility View Settings dialog

X-UA-Compatible overrides the Compatibility View Settings, so the page will render in standards mode regardless of the browser settings. This forces standards mode for:

  • intranet pages
  • external web pages when the computer administrator has chosen “Display all websites in Compatibility View” as the default—think big companies, governments, universities
  • when you unintentionally end up on the Microsoft Compatibility View List
  • cases where users have manually added your website to the list in Compatibility View Settings

DOCTYPE alone cannot do that; you will end up in one of the Compatibility View modes in these cases regardless of DOCTYPE.

If both the meta tag and the HTTP header are specified, the meta tag takes precedence.

This answer is based on examining the complete rules for deciding document mode in IE8, IE9, and IE10. Note that looking at the DOCTYPE is the very last fallback for deciding the document mode.

How can I plot a histogram such that the heights of the bars sum to 1 in matplotlib?

I know this answer is too late considering the question is dated 2010 but I came across this question as I was facing a similar problem myself. As already stated in the answer, normed=True means that the total area under the histogram is equal to 1 but the sum of heights is not equal to 1. However, I wanted to, for convenience of physical interpretation of a histogram, make one with sum of heights equal to 1.

I found a hint in the following question - Python: Histogram with area normalized to something other than 1

But I was not able to find a way of making bars mimic the histtype="step" feature hist(). This diverted me to : Matplotlib - Stepped histogram with already binned data

If the community finds it acceptable I should like to put forth a solution which synthesises ideas from both the above posts.

import matplotlib.pyplot as plt

# Let X be the array whose histogram needs to be plotted.
nx, xbins, ptchs = plt.hist(X, bins=20)
plt.clf() # Get rid of this histogram since not the one we want.

nx_frac = nx/float(len(nx)) # Each bin divided by total number of objects.
width = xbins[1] - xbins[0] # Width of each bin.
x = np.ravel(zip(xbins[:-1], xbins[:-1]+width))
y = np.ravel(zip(nx_frac,nx_frac))

plt.plot(x,y,linestyle="dashed",label="MyLabel")
#... Further formatting.

This has worked wonderfully for me though in some cases I have noticed that the left most "bar" or the right most "bar" of the histogram does not close down by touching the lowest point of the Y-axis. In such a case adding an element 0 at the begging or the end of y achieved the necessary result.

Just thought I'd share my experience. Thank you.

How to monitor the memory usage of Node.js?

On Linux/Unix (note: Mac OS is a Unix) use top and press M (Shift+M) to sort processes by memory usage.

On Windows use the Task Manager.

load scripts asynchronously

You can use LABJS or RequreJS

Script loaders like LABJS, RequireJS will improve the speed and quality of your code.

What is the difference between new/delete and malloc/free?

also,

the global new and delete can be overridden, malloc/free cannot.

further more new and delete can be overridden per type.

How to replace deprecated android.support.v4.app.ActionBarDrawerToggle

Adding only android-support-v7-appcompat.jar to library dependencies is not enough, you have also to import in your project the module that you can find in your SDK at the path \android-sdk\extras\android\support\v7\appcompatand after that add module dependencies configuring the project structure in this way

enter image description here

otherwise are included only the class files of support library and the app is not able to load the other resources causing the error.

In addition as reVerse suggested replace this

public CustomActionBarDrawerToggle(Activity mActivity,
                                           DrawerLayout mDrawerLayout) {
            super(mActivity, mDrawerLayout,new Toolbar(MyActivity.this) ,
                    R.string.ns_menu_open, R.string.ns_menu_close);
        }

with

public CustomActionBarDrawerToggle(Activity mActivity,
                                           DrawerLayout mDrawerLayout) {
            super(mActivity, mDrawerLayout, R.string.ns_menu_open, R.string.ns_menu_close);
        }

How to replace special characters in a string?

That depends on what you mean. If you just want to get rid of them, do this:
(Update: Apparently you want to keep digits as well, use the second lines in that case)

String alphaOnly = input.replaceAll("[^a-zA-Z]+","");
String alphaAndDigits = input.replaceAll("[^a-zA-Z0-9]+","");

or the equivalent:

String alphaOnly = input.replaceAll("[^\\p{Alpha}]+","");
String alphaAndDigits = input.replaceAll("[^\\p{Alpha}\\p{Digit}]+","");

(All of these can be significantly improved by precompiling the regex pattern and storing it in a constant)

Or, with Guava:

private static final CharMatcher ALNUM =
  CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z'))
  .or(CharMatcher.inRange('0', '9')).precomputed();
// ...
String alphaAndDigits = ALNUM.retainFrom(input);

But if you want to turn accented characters into something sensible that's still ascii, look at these questions:

How to send data with angularjs $http.delete() request?

A many to many relationship normally has a linking table. Consider this "link" as an entity in its own right and give it a unique id, then send that id in the delete request.

You would have a a REST resource URL like /user/role to handle operations on a user-role "link" entity.

What is the purpose of the "final" keyword in C++11 for functions?

Final cannot be applied to non-virtual functions.

error: only virtual member functions can be marked 'final'

It wouldn't be very meaningful to be able to mark a non-virtual method as 'final'. Given

struct A { void foo(); };
struct B : public A { void foo(); };
A * a = new B;
a -> foo(); // this will call A :: foo anyway, regardless of whether there is a B::foo

a->foo() will always call A::foo.

But, if A::foo was virtual, then B::foo would override it. This might be undesirable, and hence it would make sense to make the virtual function final.

The question is though, why allow final on virtual functions. If you have a deep hierarchy:

struct A            { virtual void foo(); };
struct B : public A { virtual void foo(); };
struct C : public B { virtual void foo() final; };
struct D : public C { /* cannot override foo */ };

Then the final puts a 'floor' on how much overriding can be done. Other classes can extend A and B and override their foo, but it a class extends C then it is not allowed.

So it probably doesn't make sense to make the 'top-level' foo final, but it might make sense lower down.

(I think though, there is room to extend the words final and override to non-virtual members. They would have a different meaning though.)

how to set radio button checked in edit mode in MVC razor view

To set radio button checked in edit mode in MVC razor view, please trying as follow:

<div class="col-lg-11 col-md-11">
     @Html.RadioButtonFor(m => m.Role, "1", Model.Role == 1 ? "checked" : string.Empty) 
     <span>Admin</span>
     @Html.RadioButtonFor(m => m.Role, "0", Model.Role == 0 ? "checked" : string.Empty)
     <span>User</span>
     @Html.HiddenFor(m => m.Role)
</div>

Hope it help!

Pad a number with leading zeros in JavaScript

Not a lot of "slick" going on so far:

function pad(n, width, z) {
  z = z || '0';
  n = n + '';
  return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}

When you initialize an array with a number, it creates an array with the length set to that value so that the array appears to contain that many undefined elements. Though some Array instance methods skip array elements without values, .join() doesn't, or at least not completely; it treats them as if their value is the empty string. Thus you get a copy of the zero character (or whatever "z" is) between each of the array elements; that's why there's a + 1 in there.

Example usage:

pad(10, 4);      // 0010
pad(9, 4);       // 0009
pad(123, 4);     // 0123

pad(10, 4, '-'); // --10

Grep characters before and after match?

You could use

awk '/test_pattern/ {
    match($0, /test_pattern/); print substr($0, RSTART - 10, RLENGTH + 20);
}' file

Can two Java methods have same name with different return types?

You can have two methods with the same arguments and different return types only if one of the methods is inherited and the return types are compatible.

For example:

public class A
{
    Object foo() { return null; }
}

public class B
    extends A
{
    String foo() { return null; }
}

Best way to check if a Data Table has a null value in it

DataTable dt = new DataTable();
foreach (DataRow dr in dt.Rows)
{
    if (dr["Column_Name"] == DBNull.Value)
    {
        //Do something
    }
    else
    {
        //Do something
    }
}

How to identify which columns are not "NA" per row in a matrix?

Try:

which( !is.na(p), arr.ind=TRUE)

Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:

> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3

[[2]]
[1] 4 7

[[3]]
integer(0)

[[4]]
[1] 5

[[5]]
integer(0)

Or even with smushing together with paste:

lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")

The output from which function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:

> which( !is.na(p), arr.ind=TRUE)
     row col
[1,]   1   2
[2,]   1   3
[3,]   2   4
[4,]   4   5
[5,]   2   7

Without the arr.ind parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".

> which( !is.na(p) )
[1]  6 11 17 24 32

Good tool for testing socket connections?

I also found a tool called TCP/IP Test Server [Edit: no longer available from the original developer, but still available via Brothersoft] which seems to do what I need too. But I didn't try it because it is not listed on big freeware-sites (like CNET...) and no source code is published so that it won't reassure a paranoid sysadmin.

Unrecognized escape sequence for path string containing backslashes

var foo = @"D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";

Link to add to Google calendar

I've also been successful with this URL structure:

Base URL:

https://calendar.google.com/calendar/r/eventedit?

And let's say this is my event details:

Title: Event Title
Description: Example of some description. See more at https://stackoverflow.com/questions/10488831/link-to-add-to-google-calendar
Location: 123 Some Place
Date: February 22, 2020
Start Time: 10:00am
End Time: 11:30am
Timezone: America/New York (GMT -5)

I'd convert my details into these parameters (URL encoded):

text=Event%20Title
details=Example%20of%20some%20description.%20See%20more%20at%20https%3A%2F%2Fstackoverflow.com%2Fquestions%2F10488831%2Flink-to-add-to-google-calendar
location=123%20Some%20Place%2C%20City
dates=20200222T100000/20200222T113000
ctz=America%2FNew_York

Example link:

https://calendar.google.com/calendar/r/eventedit?text=Event%20Title&details=Example%20of%20some%20description.%20See%20more%20at%20https%3A%2F%2Fstackoverflow.com%2Fquestions%2F10488831%2Flink-to-add-to-google-calendar&location=123%20Some%20Place%2C%20City&dates=20200222T100000/20200222T113000&ctz=America%2FNew_York

Please note that since I've specified a timezone with the "ctz" parameter, I used the local times for the start and end dates. Alternatively, you can use UTC dates and exclude the timezone parameter, like this:

dates=20200222T150000Z/20200222T163000Z

Example link:

https://calendar.google.com/calendar/r/eventedit?text=Event%20Title&details=Example%20of%20some%20description.%20See%20more%20at%20https%3A%2F%2Fstackoverflow.com%2Fquestions%2F10488831%2Flink-to-add-to-google-calendar&location=123%20Some%20Place%2C%20City&dates=20200222T150000Z/20200222T163000Z

Characters allowed in GET parameter

From RFC 1738 on which characters are allowed in URLs:

Only alphanumerics, the special characters "$-_.+!*'(),", and reserved characters used for their reserved purposes may be used unencoded within a URL.

The reserved characters are ";", "/", "?", ":", "@", "=" and "&", which means you would need to URL encode them if you wish to use them.

Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling

You can just pass your URL,

NSURL *url = [NSURL URLWithString:@"http://www.myurl.com/1.png"];
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data,    NSURLResponse * _Nullable response, NSError * _Nullable error) {
    if (data) {
        UIImage *image = [UIImage imageWithData:data];
        if (image) {
            dispatch_async(dispatch_get_main_queue(), ^{
                    yourimageview.image = image;
            });
        }
    }
}];
[task resume];

Uninstall Node.JS using Linux command line?

I think this works, at least partially (have not investigated): nvm uninstall <VERSION_TO_UNINSTALL> eg:

nvm uninstall 4.4.5

why I can't get value of label with jquery and javascript?

Label's aren't form elements. They don't have a value. They have innerHTML and textContent.

Thus,

$('#telefon').html() 
// or
$('#telefon').text()

or

var telefon = document.getElementById('telefon');
telefon.innerHTML;

If you are starting with your form element, check out the labels list of it. That is,

var el = $('#myformelement');
var label = $( el.prop('labels') );
// label.html();
// el.val();
// blah blah blah you get the idea

Fetch: reject promise and catch the error if status is not OK?

Thanks for the help everyone, rejecting the promise in .catch() solved my issue:

export function fetchVehicle(id) {
    return dispatch => {
        return dispatch({
            type: 'FETCH_VEHICLE',
            payload: fetch(`http://swapi.co/api/vehicles/${id}/`)
                .then(status)
                .then(res => res.json())    
                .catch(error => {
                    return Promise.reject()
                })
            });
    };
}


function status(res) {
    if (!res.ok) {
        throw new Error(res.statusText);
    }
    return res;
}

Visual Studio keyboard shortcut to display IntelliSense

If you want to change whether it highlights the best fitting possibility, use:

Ctrl + Alt + Space

Facebook api: (#4) Application request limit reached

now Application-Level Rate Limiting 200 calls per hour !

you can look this image.enter image description here

Cannot use special principal dbo: Error 15405

To fix this, open the SQL Server Management Studio and click New Query. Then type:

USE mydatabase
exec sp_changedbowner 'sa', 'true'

How can I check if some text exist or not in the page using Selenium?

string_website.py

search string in webpage

    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    browser = webdriver.Firefox()
    browser.get("https://www.python.org/")
    content=browser.page_source

    result = content.find('integrate systems')
    print ("Substring found at index:", result ) 

    if (result != -1): 
    print("Webpage OK")
    else: print("Webpage NOT OK")
    #print(content)
    browser.close()

run

python test_website.py
Substring found at index: 26722
Webpage OK


d:\tools>python test_website.py
Substring found at index: -1 ; -1 means nothing found
Webpage NOT OK

Cannot checkout, file is unmerged

I don't think execute

 git rm first_file.txt

is a good idea.

  1. when git notice your files is unmerged, you should ensure you had committed it.

  2. And then open the conflict file:

    cat first_file.txt

  3. fix the conflict

4.

git add file

git commit -m "fix conflict"

5. git push

it should works for you.

How to fix error ::Format of the initialization string does not conform to specification starting at index 0::

An unwanted single quote was my problem. Checking the connection string from the location of the index mentioned in the error string helped me spot the issue.

What is a callback URL in relation to an API?

A callback URL will be invoked by the API method you're calling after it's done. So if you call

POST /api.example.com/foo?callbackURL=http://my.server.com/bar

Then when /foo is finished, it sends a request to http://my.server.com/bar. The contents and method of that request are going to vary - check the documentation for the API you're accessing.

Grep regex NOT containing string

grep matches, grep -v does the inverse. If you need to "match A but not B" you usually use pipes:

grep "${PATT}" file | grep -v "${NOTPATT}"

Expanding tuples into arguments

This is the functional programming method. It lifts the tuple expansion feature out of syntax sugar:

apply_tuple = lambda f, t: f(*t)

Redefine apply_tuple via curry to save a lot of partial calls in the long run:

from toolz import curry
apply_tuple = curry(apply_tuple)

Example usage:

from operator import add, eq
from toolz import thread_last

thread_last(
    [(1,2), (3,4)],
    (map, apply_tuple(add)),
    list,
    (eq, [3, 7])
)
# Prints 'True'

How to create timer in angular2

If you look to run a method on ngOnInit you could do something like this:

import this 2 libraries from RXJS:

import {Observable} from 'rxjs/Rx';
import {Subscription} from "rxjs";

Then declare timer and private subscription, example:

timer= Observable.timer(1000,1000); // 1 second for 2 seconds (2000,1000) etc
private subscription: Subscription;

Last but not least run method when timer stops

ngOnInit() {
  this.subscription = this.timer.subscribe(ticks=> {
    this.populatecombobox();  //example calling a method that populates a combobox
    this.subscription.unsubscribe();  //you need to unsubscribe or it will run infinite times
  });
}

That's all, Angular 5

Why "no projects found to import"?

This answer is same as Laura's answer , however, in new eclipse versions you will not be able to see a "create project from existing source" option.

Hence you can do this instead:

  • Goto File > New > Project

  • Select the type of project, click Next

  • Uncheck Use default location

  • Click on Browse to navigate to your source folder, or type in the path to your source

  • Click Finish

Taken from this discussion forum in eclipse.org

Text in Border CSS HTML

You can use a fieldset tag.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<form>_x000D_
 <fieldset>_x000D_
  <legend>Personalia:</legend>_x000D_
  Name: <input type="text"><br>_x000D_
  Email: <input type="text"><br>_x000D_
  Date of birth: <input type="text">_x000D_
 </fieldset>_x000D_
</form>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Check this link: HTML Tag

Saving lists to txt file

@Jon's answer is great and will get you where you need to go. So why is your code printing out what it is. The answer: You're not writing out the contents of your list, but the String representation of your list itself, by an implicit call to Lists.verbList.ToString(). Object.ToString() defines the default behavior you're seeing here.

AngularJS: Service vs provider vs factory

Let's discuss the three ways of handling business logic in AngularJS in a simple way: (Inspired by Yaakov's Coursera AngularJS course)

SERVICE:

Syntax:

app.js

 var app = angular.module('ServiceExample',[]);
 var serviceExampleController =
              app.controller('ServiceExampleController', ServiceExampleController);
 var serviceExample = app.service('NameOfTheService', NameOfTheService);

 ServiceExampleController.$inject = ['NameOfTheService'] //protects from minification of js files

function ServiceExampleController(NameOfTheService){
     serviceExampleController = this;
     serviceExampleController.data = NameOfTheService.getSomeData();
 }

function NameOfTheService(){
     nameOfTheService = this;
     nameOfTheService.data = "Some Data";
     nameOfTheService.getSomeData = function(){
           return nameOfTheService.data;
     }     
}

index.html

<div ng-controller = "ServiceExampleController as serviceExample">
   {{serviceExample.data}}
</div>

Features of Service:

  1. Lazily Instantiated: If it is not injected it won't be instantiated ever. So to use it will have to inject it to a module.
  2. Singleton: If injected to multiple modules, all will have access to only one particular instance. That is why very convenient to share data across different controllers.

FACTORY

First let's have a look at the syntax:

app.js:

var app = angular.module('FactoryExample',[]);
var factoryController = app.controller('FactoryController', FactoryController);
var factoryExampleOne = app.factory('NameOfTheFactoryOne', NameOfTheFactoryOne);
var factoryExampleTwo = app.factory('NameOfTheFactoryTwo', NameOfTheFactoryTwo);

//first implementation where it returns a function
function NameOfTheFactoryOne(){
   var factory = function(){
      return new SomeService();
    }
   return factory;
}

//second implementation where an object literal would be returned
function NameOfTheFactoryTwo(){
   var factory = {
      getSomeService : function(){
          return new SomeService();
       }
    };
   return factory;
}

Now using the above two in the controller:

 var factoryOne = NameOfTheFactoryOne() //since it returns a function
 factoryOne.someMethod();

 var factoryTwo = NameOfTheFactoryTwo.getSomeService(); //accessing the object
 factoryTwo.someMethod();

Features of Factory:

  1. Follows the factory design pattern. The factory is a central place that produces new objects or functions.
  2. Not only produces singleton, but customizable services.
  3. The .service() method is a factory that always produces the same type of service, which is a singleton, and without any easy way to configure it's behavior. That .service() method is usually used as a shortcut for something that doesn't require any configuration whatsoever.

PROVIDER

Let's again have a look at the Syntax first:

angular.module('ProviderModule', [])
.controller('ProviderModuleController', ProviderModuleController)
.provider('ServiceProvider', ServiceProvider)
.config(Config); //optional

Config.$inject = ['ServiceProvider'];
function Config(ServiceProvider) {
  ServiceProvider.defaults.maxItems = 10; //some default value
}


ProviderModuleController.$inject = ['ServiceProvider'];
function ProviderModuleController(ServiceProvider) {
  //some methods
}

function ServiceProvider() {
  var provider = this;

  provider.defaults = {
    maxItems: 10
  };

  provider.$get = function () {
    var someList = new someListService(provider.defaults.maxItems);

    return someList;
  };
}

}

Features of Provider:

  1. Provider is the most flexible method of creating services in Angular.
  2. Not only we can create a factory that's dynamically configurable, but at the time of using the factory, with the provider method, we could custom configure the factory just once at the bootstrapping of our entire application.
  3. The factory can then be used throughout the application with custom settings. In other words, we can configure this factory before the application starts. In fact in the angular documentation it is mentioned that the provider method is what actually gets executed behind the scenes when we configure our services with either .service or .factory methods.
  4. The $get is a function that is directly attached to the provider instance. That function is a factory function. In other words, it's just like the one that we use to provide to the .factory method. In that function, we create our own service. This $get property, that's a function, is what makes the provider a provider. AngularJS expects the provider to have a $get property whose value is a function that Angular will treat as a factory function. But what makes this whole provider setup very special, is the fact that we can provide some config object inside the service provider, and that usually comes with defaults that we can later overwrite in the step, where we can configure the entire application.

How to set the authorization header using curl

http://curl.haxx.se/docs/httpscripting.html

See part 6. HTTP Authentication

HTTP Authentication

HTTP Authentication is the ability to tell the server your username and password so that it can verify that you're allowed to do the request you're doing. The Basic authentication used in HTTP (which is the type curl uses by default) is plain text based, which means it sends username and password only slightly obfuscated, but still fully readable by anyone that sniffs on the network between you and the remote server.

To tell curl to use a user and password for authentication:

curl --user name:password http://www.example.com

The site might require a different authentication method (check the headers returned by the server), and then --ntlm, --digest, --negotiate or even --anyauth might be options that suit you.

Sometimes your HTTP access is only available through the use of a HTTP proxy. This seems to be especially common at various companies. A HTTP proxy may require its own user and password to allow the client to get through to the Internet. To specify those with curl, run something like:

curl --proxy-user proxyuser:proxypassword curl.haxx.se

If your proxy requires the authentication to be done using the NTLM method, use --proxy-ntlm, if it requires Digest use --proxy-digest.

If you use any one these user+password options but leave out the password part, curl will prompt for the password interactively.

Do note that when a program is run, its parameters might be possible to see when listing the running processes of the system. Thus, other users may be able to watch your passwords if you pass them as plain command line options. There are ways to circumvent this.

It is worth noting that while this is how HTTP Authentication works, very many web sites will not use this concept when they provide logins etc. See the Web Login chapter further below for more details on that.

Rename package in Android Studio

If your package starts with mypackageold.something.test then you can't change to mypackagenew.somethingnew.testnew.

In this case, if I follow above accepted answer steps result will be mypackageold.somethingnew.testnew.

Only if your package starts with com.... to New package, above accepted answer will work.

So if you want to change the package from Root Level

  1. Change the Required package name inside manifest,
  2. Remove the old package and Crate New Package under Android tab,
  3. Drag all the Files from old Package to New Package,
  4. Inside the Manifest also change the package name for those files,
  5. Clean Project,
  6. Open build.gradle and update applicationId.

Opening database file from within SQLite command-line shell

I think the simplest way to just open a single database and start querying is:

sqlite> .open "test.db"
sqlite> SELECT * FROM table_name ... ;

Notice: This works only for versions 3.8.2+

get all the images from a folder in php

when you want to get all image from folder then use glob() built in function which help to get all image . But when you get all then sometime need to check that all is valid so in this case this code help you. this code will also check that it is image

  $all_files = glob("mytheme/images/myimages/*.*");
  for ($i=0; $i<count($all_files); $i++)
    {
      $image_name = $all_files[$i];
      $supported_format = array('gif','jpg','jpeg','png');
      $ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
      if (in_array($ext, $supported_format))
          {
            echo '<img src="'.$image_name .'" alt="'.$image_name.'" />'."<br /><br />";
          } else {
              continue;
          }
    }

for more information

PHP Manual

Execute combine multiple Linux commands in one line

I find lots of answer for this kind of question misleading

Modified from this post: https://www.webmasterworld.com/linux/3613813.htm

The following code will create bash window and works exactly as a bash window. Hope this helps. Too many wrong/not-working answers out there...

            Process proc;
            try {
                //create a bash window
                proc = Runtime.getRuntime().exec("/bin/bash");
                if (proc != null) {
                       BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
                       PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
                       BufferedReader err = new BufferedReader(new InputStreamReader(
                       proc.getErrorStream()));
                       //input into the bash window
                       out.println("cd /my_folder");
                       out.println("rm *.jar");
                       out.println("svn co path to repo");
                       out.println("mvn compile package install");
                       out.println("exit");
                       String line;
                        System.out.println("----printing output-----");
                          while ((line = in.readLine()) != null) {
                             System.out.println(line);
                          }
                          while((line = err.readLine()) != null) {
                             //read errors
                          }
                          proc.waitFor();
                          in.close();
                          out.close();
                          err.close();
                          proc.destroy();
                }

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

What are the "spec.ts" files generated by Angular CLI for?

The .spec.ts files are for unit tests for individual components. You can run Karma task runner through ng test. In order to see code coverage of unit test cases for particular components run ng test --code-coverage

how to reset <input type = "file">

SOLUTION

The following code worked for me with jQuery. It works in every browser and allows to preserve events and custom properties.

var $el = $('#uploadCaptureInputFile');
$el.wrap('<form>').closest('form').get(0).reset();
$el.unwrap();

DEMO

See this jsFiddle for code and demonstration.

LINKS

See How to reset file input with JavaScript for more information.

Maven plugin in Eclipse - Settings.xml file is missing

Working on Mac I followed the answer of Sean Patrick Floyd placing a settings.xml like above in my user folder /Users/user/.m2/

But this did not help. So I opened a Terminal and did a ls -la on the folder. This was showing

-rw-r--r--@

thus staff and everone can at least read the file. So I wondered if the message isn't wrong and if the real cause is the lack of write permissions. I set the file to:

-rw-r--rw-@

This did it. The message disappeared.

How to find which git branch I am on when my disk is mounted on other server

You can look at the HEAD pointer (stored in .git/HEAD) to see the sha1 of the currently checked-out commit, or it will be of the format ref: refs/heads/foo for example if you have a local ref foo checked out.

EDIT: If you'd like to do this from a shell, git symbolic-ref HEAD will give you the same information.

How can I find where I will be redirected using cURL?

Lot's of regex here, despite the fact i really like them this way might be more stable to me:

$resultCurl=curl_exec($curl); //get curl result
//Optional line if you want to store the http status code
$headerHttpCode=curl_getinfo($curl,CURLINFO_HTTP_CODE);

//let's use dom and xpath
$dom = new \DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($resultCurl, LIBXML_HTML_NODEFDTD);
libxml_use_internal_errors(false);
$xpath = new \DOMXPath($dom);
$head=$xpath->query("/html/body/p/a/@href");

$newUrl=$head[0]->nodeValue;

The location part is a link in the HTML sent by apache. So Xpath is perfect to recover it.

map function for objects (instead of arrays)

There is no native map to the Object object, but how about this:

_x000D_
_x000D_
var myObject = { 'a': 1, 'b': 2, 'c': 3 };_x000D_
_x000D_
Object.keys(myObject).map(function(key, index) {_x000D_
  myObject[key] *= 2;_x000D_
});_x000D_
_x000D_
console.log(myObject);_x000D_
// => { 'a': 2, 'b': 4, 'c': 6 }
_x000D_
_x000D_
_x000D_

But you could easily iterate over an object using for ... in:

_x000D_
_x000D_
var myObject = { 'a': 1, 'b': 2, 'c': 3 };_x000D_
_x000D_
for (var key in myObject) {_x000D_
  if (myObject.hasOwnProperty(key)) {_x000D_
    myObject[key] *= 2;_x000D_
  }_x000D_
}_x000D_
_x000D_
console.log(myObject);_x000D_
// { 'a': 2, 'b': 4, 'c': 6 }
_x000D_
_x000D_
_x000D_

Update

A lot of people are mentioning that the previous methods do not return a new object, but rather operate on the object itself. For that matter I wanted to add another solution that returns a new object and leaves the original object as it is:

_x000D_
_x000D_
var myObject = { 'a': 1, 'b': 2, 'c': 3 };_x000D_
_x000D_
// returns a new object with the values at each key mapped using mapFn(value)_x000D_
function objectMap(object, mapFn) {_x000D_
  return Object.keys(object).reduce(function(result, key) {_x000D_
    result[key] = mapFn(object[key])_x000D_
    return result_x000D_
  }, {})_x000D_
}_x000D_
_x000D_
var newObject = objectMap(myObject, function(value) {_x000D_
  return value * 2_x000D_
})_x000D_
_x000D_
console.log(newObject);_x000D_
// => { 'a': 2, 'b': 4, 'c': 6 }_x000D_
_x000D_
console.log(myObject);_x000D_
// => { 'a': 1, 'b': 2, 'c': 3 }
_x000D_
_x000D_
_x000D_

Array.prototype.reduce reduces an array to a single value by somewhat merging the previous value with the current. The chain is initialized by an empty object {}. On every iteration a new key of myObject is added with twice the key as the value.

Update

With new ES6 features, there is a more elegant way to express objectMap.

_x000D_
_x000D_
const objectMap = (obj, fn) =>_x000D_
  Object.fromEntries(_x000D_
    Object.entries(obj).map(_x000D_
      ([k, v], i) => [k, fn(v, k, i)]_x000D_
    )_x000D_
  )_x000D_
  _x000D_
const myObject = { a: 1, b: 2, c: 3 }_x000D_
_x000D_
console.log(objectMap(myObject, v => 2 * v)) 
_x000D_
_x000D_
_x000D_

Why does Path.Combine not properly concatenate filenames that start with Path.DirectorySeparatorChar?

This code should do the trick:

        string strFinalPath = string.Empty;
        string normalizedFirstPath = Path1.TrimEnd(new char[] { '\\' });
        string normalizedSecondPath = Path2.TrimStart(new char[] { '\\' });
        strFinalPath =  Path.Combine(normalizedFirstPath, normalizedSecondPath);
        return strFinalPath;

Is there a way to specify a default property value in Spring XML?

Are you looking for the PropertyOverrideConfigurer documented here

http://static.springsource.org/spring/docs/2.5.x/reference/beans.html#beans-factory-overrideconfigurer

The PropertyOverrideConfigurer, another bean factory post-processor, is similar to the PropertyPlaceholderConfigurer, but in contrast to the latter, the original definitions can have default values or no values at all for bean properties. If an overriding Properties file does not have an entry for a certain bean property, the default context definition is used.

Add floating point value to android resources/values

There is a solution:

<resources>
    <item name="text_line_spacing" format="float" type="dimen">1.0</item>
</resources>

In this way, your float number will be under @dimen. Notice that you can use other "format" and/or "type" modifiers, where format stands for:

Format = enclosing data type:

  • float
  • boolean
  • fraction
  • integer
  • ...

and type stands for:

Type = resource type (referenced with R.XXXXX.name):

  • color
  • dimen
  • string
  • style
  • etc...

To fetch resource from code, you should use this snippet:

TypedValue outValue = new TypedValue();
getResources().getValue(R.dimen.text_line_spacing, outValue, true);
float value = outValue.getFloat();  

I know that this is confusing (you'd expect call like getResources().getDimension(R.dimen.text_line_spacing)), but Android dimensions have special treatment and pure "float" number is not valid dimension.


Additionally, there is small "hack" to put float number into dimension, but be WARNED that this is really hack, and you are risking chance to lose float range and precision.

<resources>
    <dimen name="text_line_spacing">2.025px</dimen>
</resources>

and from code, you can get that float by

float lineSpacing = getResources().getDimension(R.dimen.text_line_spacing);

in this case, value of lineSpacing is 2.024993896484375, and not 2.025 as you would expected.

Convert JSON String to JSON Object c#

if you don't want or need a typed object try:

using Newtonsoft.Json;
// ...   
dynamic json  = JsonConvert.DeserializeObject(str);

or try for a typed object try:

Foo json  = JsonConvert.DeserializeObject<Foo>(str)

How to add a Try/Catch to SQL Stored Procedure

Create Proc[usp_mquestions]  
( 
 @title  nvarchar(500),   --0
 @tags  nvarchar(max),   --1
 @category  nvarchar(200),   --2
 @ispoll  char(1),   --3
 @descriptions  nvarchar(max),   --4
)              
 AS  
 BEGIN TRY




BEGIN
DECLARE @message varchar(1000); 
DECLARE @tempid bigint; 

IF((SELECT count(id) from  [xyz] WHERE title=@title)>0)
BEGIN
SELECT 'record already existed.';
END
ELSE
BEGIN               


if @id=0 
begin 
select @tempid =id from [xyz] where id=@id;

if @tempid is null 
BEGIN 
        INSERT INTO xyz
        (entrydate,updatedate)
        VALUES
        (GETDATE(),GETDATE())

        SET @tempid=@@IDENTITY;
 END 
END 
ELSE 
BEGIN 
set @tempid=@id 
END 
if @tempid>0 
BEGIN 

    -- Updation of table begin--


UPDATE  tab_questions
set title=@title, --0 
 tags=@tags, --1 
 category=@category, --2 
 ispoll=@ispoll, --3 
 descriptions=@descriptions, --4 
 status=@status, --5

WHERE id=@tempid ; --9 ;


IF @id=0 
BEGIN 
SET @message= 'success:Record added successfully:'+ convert(varchar(10), @tempid)
END 
ELSE 
BEGIN 
SET @message= 'success:Record updated successfully.:'+ convert(varchar(10), @tempid)

END 
END 
ELSE 
BEGIN 
SET @message= 'failed:invalid request:'+convert(varchar(10), @tempid)
END 

END
END

END TRY
BEGIN CATCH
    SET @message='failed:'+ ERROR_MESSAGE();
END CATCH
SELECT @message;

Ordering by the order of values in a SQL IN() clause

If you want to do arbitrary sorting on a query using values inputted by the query in MS SQL Server 2008+, it can be done by creating a table on the fly and doing a join like so (using nomenclature from OP).

SELECT table1.name, table1.description ... 
FROM (VALUES (id1,1), (id2,2), (id3,3) ...) AS orderTbl(orderKey, orderIdx) 
LEFT JOIN table1 ON orderTbl.orderKey=table1.id
ORDER BY orderTbl.orderIdx

If you replace the VALUES statement with something else that does the same thing, but in ANSI SQL, then this should work on any SQL database.

Note: The second column in the created table (orderTbl.orderIdx) is necessary when querying record sets larger than 100 or so. I originally didn't have an orderIdx column, but found that with result sets larger than 100 I had to explicitly sort by that column; in SQL Server Express 2014 anyways.

What does the symbol \0 mean in a string-literal?

char str[]= "Hello\0";

That would be 7 bytes.

In memory it'd be:

48 65 6C 6C 6F 00 00
H  e  l  l  o  \0 \0

Edit:

  • What does the \0 symbol mean in a C string?
    It's the "end" of a string. A null character. In memory, it's actually a Zero. Usually functions that handle char arrays look for this character, as this is the end of the message. I'll put an example at the end.

  • What is the length of str array? (Answered before the edit part)
    7

  • and with how much 0s it is ending?
    You array has two "spaces" with zero; str[5]=str[6]='\0'=0

Extra example:
Let's assume you have a function that prints the content of that text array. You could define it as:

char str[40];

Now, you could change the content of that array (I won't get into details on how to), so that it contains the message: "This is just a printing test" In memory, you should have something like:

54 68 69 73 20 69 73 20 6a 75 73 74 20 61 20 70 72 69 6e 74
69 6e 67 20 74 65 73 74 00 00 00 00 00 00 00 00 00 00 00 00

So you print that char array. And then you want a new message. Let's say just "Hello"

48 65 6c 6c 6f 00 73 20 6a 75 73 74 20 61 20 70 72 69 6e 74
69 6e 67 20 74 65 73 74 00 00 00 00 00 00 00 00 00 00 00 00

Notice the 00 on str[5]. That's how the print function will know how much it actually needs to send, despite the actual longitude of the vector and the whole content.

(Mac) -bash: __git_ps1: command not found

For macports I had to add: source /opt/local/share/git-core/git-prompt.sh to my ./profile

Disable form auto submit on button click

You could just try using return false (return false overrides default behaviour on every DOM element) like that :

myform.onsubmit = function ()
{ 
  // do what you want
  return false
}

and then submit your form using myform.submit()

or alternatively :

mybutton.onclick = function () 
{
   // do what you want
   return false
}

Also, if you use type="button" your form will not be submitted.

What's the best UML diagramming tool?

I recommend Software Ideas Modeler. It has a lot of features and an intuitive GUI.

Close Bootstrap Modal

you can use;

$('#' + $('.modal.show').attr('id')).modal('hide');

What is the best way to manage a user's session in React?

There is a React module called react-client-session that makes storing client side session data very easy. The git repo is here.

This is implemented in a similar way as the closure approach in my other answer, however it also supports persistence using 3 different persistence stores. The default store is memory(not persistent).

  1. Cookie
  2. localStorage
  3. sessionStorage

After installing, just set the desired store type where you mount the root component ...

import ReactSession from 'react-client-session';

ReactSession.setStoreType("localStorage");

... and set/get key value pairs from anywhere in your app:

import ReactSession from 'react-client-session';

ReactSession.set("username", "Bob");
ReactSession.get("username");  // Returns "Bob"

Spring data JPA query with parameter properties

Define the query method with signatures as follows.

@Query(select p from Person p where p.forename = :forename and p.surname = :surname)
User findByForenameAndSurname(@Param("surname") String lastname,
                             @Param("forename") String firstname);
}

For further details, check the Spring Data JPA reference

.NET HashTable Vs Dictionary - Can the Dictionary be as fast?

Dictionary is faster than hashtable as dictionary is a generic strong type. Hashtable is slower as it takes object as data type which leads to boxing and unboxing.

bootstrap 3 wrap text content within div for horizontal alignment

Now Update word-wrap is replace by :

overflow-wrap:break-word;

Compatible old navigator and css 3 it's good alternative !

it's evolution of word-wrap ( since 2012... )

See more information : https://www.w3.org/TR/css-text-3/#overflow-wrap

See compatibility full : http://caniuse.com/#search=overflow-wrap

How to format a numeric column as phone number in SQL

Solutions that use SUBSTRING and concatenation + are nearly independent of RDBMS. Here is a short solution that is specific to SQL Server:

declare @x int = 123456789
select stuff(stuff(@x, 4, 0, '-'), 8, 0, '-')

What should I set JAVA_HOME environment variable on macOS X 10.6?

It is recommended to check default terminal shell before set JAVA_HOME environment variable, via following commands:

$ echo $SHELL
/bin/bash

If your default terminal is /bin/bash (Bash), then you should use @hygull method

If your default terminal is /bin/zsh (Z Shell), then you should set these environment variable in ~/.zshenv file with following contents:

export JAVA_HOME="$(/usr/libexec/java_home)"

Similarly, any other terminal type not mentioned above, you should set environment variable in its respective terminal env file.

This method tested working in macOS Mojave Version 10.14.6.

How to loop through all the files in a directory in c # .net?

try below code

Directory.GetFiles(txtFolderPath.Text, "*ProfileHandler.cs",SearchOption.AllDirectories)

Add resources, config files to your jar using gradle

Be aware that the path under src/main/resources must match the package path of your .class files wishing to access the resource. See my answer here.

How do I check if a string is valid JSON in Python?

I came up with an generic, interesting solution to this problem:

class SafeInvocator(object):
    def __init__(self, module):
        self._module = module

    def _safe(self, func):
        def inner(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except:
                return None

        return inner

    def __getattr__(self, item):
        obj = getattr(self.module, item)
        return self._safe(obj) if hasattr(obj, '__call__') else obj

and you can use it like so:

safe_json = SafeInvocator(json)
text = "{'foo':'bar'}"
item = safe_json.loads(text)
if item:
    # do something

Is there a better way to do optional function parameters in JavaScript?

Similar to Oli's answer, I use an argument Object and an Object which defines the default values. With a little bit of sugar...

/**
 * Updates an object's properties with other objects' properties. All
 * additional non-falsy arguments will have their properties copied to the
 * destination object, in the order given.
 */
function extend(dest) {
  for (var i = 1, l = arguments.length; i < l; i++) {
    var src = arguments[i]
    if (!src) {
      continue
    }
    for (var property in src) {
      if (src.hasOwnProperty(property)) {
        dest[property] = src[property]
      }
    }
  }
  return dest
}

/**
 * Inherit another function's prototype without invoking the function.
 */
function inherits(child, parent) {
  var F = function() {}
  F.prototype = parent.prototype
  child.prototype = new F()
  child.prototype.constructor = child
  return child
}

...this can be made a bit nicer.

function Field(kwargs) {
  kwargs = extend({
    required: true, widget: null, label: null, initial: null,
    helpText: null, errorMessages: null
  }, kwargs)
  this.required = kwargs.required
  this.label = kwargs.label
  this.initial = kwargs.initial
  // ...and so on...
}

function CharField(kwargs) {
  kwargs = extend({
    maxLength: null, minLength: null
  }, kwargs)
  this.maxLength = kwargs.maxLength
  this.minLength = kwargs.minLength
  Field.call(this, kwargs)
}
inherits(CharField, Field)

What's nice about this method?

  • You can omit as many arguments as you like - if you only want to override the value of one argument, you can just provide that argument, instead of having to explicitly pass undefined when, say there are 5 arguments and you only want to customise the last one, as you would have to do with some of the other methods suggested.
  • When working with a constructor Function for an object which inherits from another, it's easy to accept any arguments which are required by the constructor of the Object you're inheriting from, as you don't have to name those arguments in your constructor signature, or even provide your own defaults (let the parent Object's constructor do that for you, as seen above when CharField calls Field's constructor).
  • Child objects in inheritance hierarchies can customise arguments for their parent constructor as they see fit, enforcing their own default values or ensuring that a certain value will always be used.

how to compare the Java Byte[] array?

Try for this:

boolean blnResult = Arrays.equals(byteArray1, byteArray2);

I am also not sure about this, but try this may be it works.

Find common substring between two strings

def matchingString(x,y):
    match=''
    for i in range(0,len(x)):
        for j in range(0,len(y)):
            k=1
            # now applying while condition untill we find a substring match and length of substring is less than length of x and y
            while (i+k <= len(x) and j+k <= len(y) and x[i:i+k]==y[j:j+k]):
                if len(match) <= len(x[i:i+k]):
                   match = x[i:i+k]
                k=k+1
    return match  

print matchingString('apple','ale') #le
print matchingString('apple pie available','apple pies') #apple pie     

React - Component Full Screen (with height 100%)

#app {
  height: 100%;
  min-height: 100vh;
}

Always full height of view min

How can I connect to MySQL on a WAMP server?

Change localhost:8080 to localhost:3306.

'Class' does not contain a definition for 'Method'

Today I encountered a problem with the exact same symptoms as you describe. I closed all files and restarted VS only to find out that some files disappeared from the Solution Explorer.

The following solved my problem: by selecting the current project in the Solution Explorer, a little icon Show all files appears on the top bar. Right-clicking the file and selecting Include In Project does the thing.

Credit

SQL LEFT-JOIN on 2 fields for MySQL

Let's try this way:

select 
    a.ip, 
    a.os, 
    a.hostname, 
    a.port, 
    a.protocol, 
    b.state
from a
left join b 
    on a.ip = b.ip 
        and a.port = b.port /*if you has to filter by columns from right table , then add this condition in ON clause*/
where a.somecolumn = somevalue /*if you have to filter by some column from left table, then add it to where condition*/

So, in where clause you can filter result set by column from right table only on this way:

...
where b.somecolumn <> (=) null

Find the IP address of the client in an SSH session

I'm getting the following output from who -m --ips on Debian 10:

root pts/0 Dec 4 06:45 123.123.123.123

Looks like a new column was added, so {print $5} or "take 5th column" attempts don't work anymore.

Try this:

who -m --ips | egrep -o '([0-9]{1,3}\.){3}[0-9]{1,3}'

Source:

How to generate a random integer number from within a range

As said before modulo isn't sufficient because it skews the distribution. Heres my code which masks off bits and uses them to ensure the distribution isn't skewed.

static uint32_t randomInRange(uint32_t a,uint32_t b) {
    uint32_t v;
    uint32_t range;
    uint32_t upper;
    uint32_t lower;
    uint32_t mask;

    if(a == b) {
        return a;
    }

    if(a > b) {
        upper = a;
        lower = b;
    } else {
        upper = b;
        lower = a; 
    }

    range = upper - lower;

    mask = 0;
    //XXX calculate range with log and mask? nah, too lazy :).
    while(1) {
        if(mask >= range) {
            break;
        }
        mask = (mask << 1) | 1;
    }


    while(1) {
        v = rand() & mask;
        if(v <= range) {
            return lower + v;
        }
    }

}

The following simple code lets you look at the distribution:

int main() {

    unsigned long long int i;


    unsigned int n = 10;
    unsigned int numbers[n];


    for (i = 0; i < n; i++) {
        numbers[i] = 0;
    }

    for (i = 0 ; i < 10000000 ; i++){
        uint32_t rand = random_in_range(0,n - 1);
        if(rand >= n){
            printf("bug: rand out of range %u\n",(unsigned int)rand);
            return 1;
        }
        numbers[rand] += 1;
    }

    for(i = 0; i < n; i++) {
        printf("%u: %u\n",i,numbers[i]);
    }

}

ERROR Source option 1.5 is no longer supported. Use 1.6 or later

For me the solution was to set the version of the maven compiler plugin to 3.8.0 and specify the release (9 for in your case, 11 in mine)

    <plugin>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.8.0</version>
      <configuration>
        <release>11</release>
      </configuration>
    </plugin>

Java verify void method calls n times with Mockito

The necessary method is Mockito#verify:

public static <T> T verify(T mock,
                           VerificationMode mode)

mock is your mocked object and mode is the VerificationMode that describes how the mock should be verified. Possible modes are:

verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");

You'll need these static imports from the Mockito class in order to use the verify method and these verification modes:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

So in your case the correct syntax will be:

Mockito.verify(mock, times(4)).send()

This verifies that the method send was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.


If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode. A simple

verify(mock).someMethod("was called once");

would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");.


It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");, but we can write

verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");

instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.

How to create module-wide variables in Python?

For this, you need to declare the variable as global. However, a global variable is also accessible from outside the module by using module_name.var_name. Add this as the first line of your module:

global __DBNAME__

With MySQL, how can I generate a column containing the record index in a table?

You can also use

SELECT @curRow := ifnull(@curRow,0) + 1 Row, ...

to initialise the counter variable.

How do I move an existing Git submodule within a Git repository?

The most modern answer, taken from Valloric's comment above:

  1. Upgrade to Git 1.9.3 (or 2.18 if the submodule contains nested submodules)
  2. git mv old/submod new/submod
  3. Afterwards the .gitmodules and the submodule directory are already staged for a commit (you can verify this with git status.)
  4. Commit the changes with git commitand you're good to go!

Done!

Write bytes to file

Try this:

private byte[] Hex2Bin(string hex) 
{
 if ((hex == null) || (hex.Length < 1)) {
  return new byte[0];
 }
 int num = hex.Length / 2;
 byte[] buffer = new byte[num];
 num *= 2;
 for (int i = 0; i < num; i++) {
  int num3 = int.Parse(hex.Substring(i, 2), NumberStyles.HexNumber);
  buffer[i / 2] = (byte) num3;
  i++;
 }
 return buffer;
}

private string Bin2Hex(byte[] binary) 
{
 StringBuilder builder = new StringBuilder();
 foreach(byte num in binary) {
  if (num > 15) {
   builder.AppendFormat("{0:X}", num);
  } else {
   builder.AppendFormat("0{0:X}", num); /////// ?? 15 ???? 0
  }
 }
 return builder.ToString();
}

How can I reset eclipse to default settings?

You can reset settings for eclipse by deleting .metadata folder from your current workspace.

This will however remove all projects from your project explorer NOT workspace. So dont worry your projects have not gone anywhere.

You can import projects from your workspace like this : just make sure that you uncheck "Copy project into workspace".

import Have a look here : import project in eclipse

git diff file against its last change

If you are fine using a graphical tool this works very well:

gitk <file>

gitk now shows all commits where the file has been updated. Marking a commit will show you the diff against the previous commit in the list. This also works for directories, but then you also get to select the file to diff for the selected commit. Super useful!

How can I set the 'backend' in matplotlib in Python?

I hit this when trying to compile python, numpy, scipy, matplotlib in my own VIRTUAL_ENV

Before installing matplotlib you have to build and install: pygobject pycairo pygtk

And then do it with matplotlib: Before building matplotlib check with 'python ./setup.py build --help' if 'gtkagg' backend is enabled. Then build and install

Before export PKG_CONFIG_PATH=$VIRTUAL_ENV/lib/pkgconfig

MySQL, Check if a column exists in a table with SQL

I threw this stored procedure together with a start from @lain's comments above, kind of nice if you need to call it more than a few times (and not needing php):

delimiter //
-- ------------------------------------------------------------
-- Use the inforamtion_schema to tell if a field exists.
-- Optional param dbName, defaults to current database
-- ------------------------------------------------------------
CREATE PROCEDURE fieldExists (
OUT _exists BOOLEAN,      -- return value
IN tableName CHAR(255),   -- name of table to look for
IN columnName CHAR(255),  -- name of column to look for
IN dbName CHAR(255)       -- optional specific db
) BEGIN
-- try to lookup db if none provided
SET @_dbName := IF(dbName IS NULL, database(), dbName);

IF CHAR_LENGTH(@_dbName) = 0
THEN -- no specific or current db to check against
  SELECT FALSE INTO _exists;
ELSE -- we have a db to work with
  SELECT IF(count(*) > 0, TRUE, FALSE) INTO _exists
  FROM information_schema.COLUMNS c
  WHERE 
  c.TABLE_SCHEMA    = @_dbName
  AND c.TABLE_NAME  = tableName
  AND c.COLUMN_NAME = columnName;
END IF;
END //
delimiter ;

Working with fieldExists

mysql> call fieldExists(@_exists, 'jos_vm_product', 'child_option', NULL) //
Query OK, 0 rows affected (0.01 sec)

mysql> select @_exists //
+----------+
| @_exists |
+----------+
|        0 |
+----------+
1 row in set (0.00 sec)

mysql> call fieldExists(@_exists, 'jos_vm_product', 'child_options', 'etrophies') //
Query OK, 0 rows affected (0.01 sec)

mysql> select @_exists //
+----------+
| @_exists |
+----------+
|        1 |
+----------+

What are the various "Build action" settings in Visual Studio project properties and what do they do?

VS2010 has a property for 'Build Action', and also for 'Copy to Output Directory'. So an action of 'None' will still copy over to the build directory if the copy property is set to 'Copy if Newer' or 'Copy Always'.

So a Build Action of 'Content' should be reserved to indicate content you will access via 'Application.GetContentStream'

I used the 'Build Action' setting of 'None' and the 'Copy to Output Direcotry' setting of 'Copy if Newer' for some externally linked .config includes.

G.

twitter bootstrap 3.0 typeahead ajax example

<input id="typeahead-input" type="text" data-provide="typeahead" />

<script type="text/javascript">
var data = ["Aamir", "Amol", "Ayesh", "Sameera", "Sumera", "Kajol", "Kamal",
  "Akash", "Robin", "Roshan", "Aryan"];
$(function() {
    $('#typeahead-input').typeahead({
        source: function (query, process) {
               process(data);
            });
        }
    });
});
</script>

how to automatically scroll down a html page?

You can use two different techniques to achieve this.

The first one is with javascript: set the scrollTop property of the scrollable element (e.g. document.body.scrollTop = 1000;).

The second is setting the link to point to a specific id in the page e.g.

<a href="mypage.html#sectionOne">section one</a>

Then if in your target page you'll have that ID the page will be scrolled automatically.

How to split a string in two and store it in a field

I would suggest the following:

String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName); 

How to prevent a browser from storing passwords

This is not possible in modern browsers, and for good reason. Modern browsers offer password managers, which enable users to use stronger passwords than they would usually.

As explained by MDN: How to Turn Off Form Autocompletion:

Modern browsers implement integrated password management: when the user enters a username and password for a site, the browser offers to remember it for the user. When the user visits the site again, the browser autofills the login fields with the stored values.

Additionally, the browser enables the user to choose a master password that the browser will use to encrypt stored login details.

Even without a master password, in-browser password management is generally seen as a net gain for security. Since users do not have to remember passwords that the browser stores for them, they are able to choose stronger passwords than they would otherwise.

For this reason, many modern browsers do not support autocomplete="off" for login fields:

  • If a site sets autocomplete="off" for a form, and the form includes username and password input fields, then the browser will still offer to remember this login, and if the user agrees, the browser will autofill those fields the next time the user visits the page.

  • If a site sets autocomplete="off" for username and password input fields, then the browser will still offer to remember this login, and if the user agrees, the browser will autofill those fields the next time the user visits the page.

This is the behavior in Firefox (since version 38), Google Chrome (since 34), and Internet Explorer (since version 11).

If an author would like to prevent the autofilling of password fields in user management pages where a user can specify a new password for someone other than themself, autocomplete="new-password" should be specified, though support for this has not been implemented in all browsers yet.

What is a lambda expression in C++11?

Answers

Q: What is a lambda expression in C++11?

A: Under the hood, it is the object of an autogenerated class with overloading operator() const. Such object is called closure and created by compiler. This 'closure' concept is near with the bind concept from C++11. But lambdas typically generate better code. And calls through closures allow full inlining.

Q: When would I use one?

A: To define "simple and small logic" and ask compiler perform generation from previous question. You give a compiler some expressions which you want to be inside operator(). All other stuff compiler will generate to you.

Q: What class of problem do they solve that wasn't possible prior to their introduction?

A: It is some kind of syntax sugar like operators overloading instead of functions for custom add, subrtact operations...But it save more lines of unneeded code to wrap 1-3 lines of real logic to some classes, and etc.! Some engineers think that if the number of lines is smaller then there is a less chance to make errors in it (I'm also think so)

Example of usage

auto x = [=](int arg1){printf("%i", arg1); };
void(*f)(int) = x;
f(1);
x(1);

Extras about lambdas, not covered by question. Ignore this section if you're not interest

1. Captured values. What you can to capture

1.1. You can reference to a variable with static storage duration in lambdas. They all are captured.

1.2. You can use lambda for capture values "by value". In such case captured vars will be copied to the function object (closure).

[captureVar1,captureVar2](int arg1){}

1.3. You can capture be reference. & -- in this context mean reference, not pointers.

   [&captureVar1,&captureVar2](int arg1){}

1.4. It exists notation to capture all non-static vars by value, or by reference

  [=](int arg1){} // capture all not-static vars by value

  [&](int arg1){} // capture all not-static vars by reference

1.5. It exists notation to capture all non-static vars by value, or by reference and specify smth. more. Examples: Capture all not-static vars by value, but by reference capture Param2

[=,&Param2](int arg1){} 

Capture all not-static vars by reference, but by value capture Param2

[&,Param2](int arg1){} 

2. Return type deduction

2.1. Lambda return type can be deduced if lambda is one expression. Or you can explicitly specify it.

[=](int arg1)->trailing_return_type{return trailing_return_type();}

If lambda has more then one expression, then return type must be specified via trailing return type. Also, similar syntax can be applied to auto functions and member-functions

3. Captured values. What you can not capture

3.1. You can capture only local vars, not member variable of the object.

4. ?onversions

4.1 !! Lambda is not a function pointer and it is not an anonymous function, but capture-less lambdas can be implicitly converted to a function pointer.

p.s.

  1. More about lambda grammar information can be found in Working draft for Programming Language C++ #337, 2012-01-16, 5.1.2. Lambda Expressions, p.88

  2. In C++14 the extra feature which has named as "init capture" have been added. It allow to perform arbitarily declaration of closure data members:

    auto toFloat = [](int value) { return float(value);};
    auto interpolate = [min = toFloat(0), max = toFloat(255)](int value)->float { return (value - min) / (max - min);};
    

How do I display an alert dialog on Android?

I have created a dialog for asking a Person whether he wants to call a Person or not.

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

public class Firstclass extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.first);

        ImageView imageViewCall = (ImageView) findViewById(R.id.ring_mig);

        imageViewCall.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v)
            {
                try
                {
                    showDialog("0728570527");
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        });
    }

    public void showDialog(final String phone) throws Exception
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(Firstclass.this);

        builder.setMessage("Ring: " + phone);

        builder.setPositiveButton("Ring", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                Intent callIntent = new Intent(Intent.ACTION_DIAL);// (Intent.ACTION_CALL);

                callIntent.setData(Uri.parse("tel:" + phone));

                startActivity(callIntent);

                dialog.dismiss();
            }
        });

        builder.setNegativeButton("Avbryt", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();
            }
        });

        builder.show();
    }
}

What is the difference between loose coupling and tight coupling in the object oriented paradigm?

In object oriented design, the amount of coupling refers to how much the design of one class depends on the design of another class. In other words, how often do changes in class A force related changes in class B? Tight coupling means the two classes often change together, loose coupling means they are mostly independent. In general, loose coupling is recommended because it's easier to test and maintain.

You may find this paper by Martin Fowler (PDF) helpful.

Create a text file for download on-the-fly

No need to store it anywhere. Just output the content with the appropriate content type.

<?php
    header('Content-type: text/plain');
?>Hello, world.

Add content-disposition if you wish to trigger a download prompt.

header('Content-Disposition: attachment; filename="default-filename.txt"');

Python vs Cpython

implementation means what language was used to implement Python and not how python Code would be implemented. The advantage of using CPython is the availability of C Run-time as well as easy integration with C/C++.

So CPython was originally implemented using C. There were other forks to the original implementation which enabled Python to lever-edge Java (JYthon) or .NET Runtime (IronPython).

Based on which Implementation you use, library availability might vary, for example Ctypes is not available in Jython, so any library which uses ctypes would not work in Jython. Similarly, if you want to use a Java Class, you cannot directly do so from CPython. You either need a glue (JEPP) or need to use Jython (The Java Implementation of Python)

How to find all occurrences of an element in a list

more_itertools.locate finds indices for all items that satisfy a condition.

from more_itertools import locate


list(locate([0, 1, 1, 0, 1, 0, 0]))
# [1, 2, 4]

list(locate(['a', 'b', 'c', 'b'], lambda x: x == 'b'))
# [1, 3]

more_itertools is a third-party library > pip install more_itertools.

Jmeter - get current date and time

Use ${__time(yyyy-MM-dd'T'hh:mm:ss)} to convert time into a particular timeformat. Here are other formats that you can use:

yyyy/MM/dd HH:mm:ss.SSS
yyyy/MM/dd HH:mm:ss
yyyy-MM-dd HH:mm:ss.SSS
yyyy-MM-dd HH:mm:ss
MM/dd/yy HH:mm:ss

You can use Z character to get milliseconds too. For example:

yyyy/MM/dd HH:mm:ssZ => 2017-01-25T10:29:00-0700
yyyy/MM/dd HH:mm:ss.SSS'Z' => 2017-01-25T10:28:49.549Z

Most of the time yyyy/MM/dd HH:mm:ss.SSS'Z' is required in some APIs. It is better to know how to convert time into this format.

Java Reflection: How to get the name of a variable?

As of Java 8, some local variable name information is available through reflection. See the "Update" section below.

Complete information is often stored in class files. One compile-time optimization is to remove it, saving space (and providing some obsfuscation). However, when it is is present, each method has a local variable table attribute that lists the type and name of local variables, and the range of instructions where they are in scope.

Perhaps a byte-code engineering library like ASM would allow you to inspect this information at runtime. The only reasonable place I can think of for needing this information is in a development tool, and so byte-code engineering is likely to be useful for other purposes too.


Update: Limited support for this was added to Java 8. Parameter (a special class of local variable) names are now available via reflection. Among other purposes, this can help to replace @ParameterName annotations used by dependency injection containers.

how to print float value upto 2 decimal place without rounding off

i'd suggest shorter and faster approach:

printf("%.2f", ((signed long)(fVal * 100) * 0.01f));

this way you won't overflow int, plus multiplication by 100 shouldn't influence the significand/mantissa itself, because the only thing that really is changing is exponent.

Target elements with multiple classes, within one rule

.border-blue.background { ... } is for one item with multiple classes.
.border-blue, .background { ... } is for multiple items each with their own class.
.border-blue .background { ... } is for one item where '.background' is the child of '.border-blue'.

See Chris' answer for a more thorough explanation.

How to clear/remove observable bindings in Knockout.js?

Have you thought about this:

try {
    ko.applyBindings(PersonListViewModel);
}
catch (err) {
    console.log(err.message);
}

I came up with this because in Knockout, i found this code

    var alreadyBound = ko.utils.domData.get(node, boundElementDomDataKey);
    if (!sourceBindings) {
        if (alreadyBound) {
            throw Error("You cannot apply bindings multiple times to the same element.");
        }
        ko.utils.domData.set(node, boundElementDomDataKey, true);
    }

So to me its not really an issue that its already bound, its that the error was not caught and dealt with...

Beautiful Soup and extracting a div and its contents by ID

The Id property is always uniquely identified. That means you can use it directly without even specifying the element. Therefore, it is a plus point if your elements have it to parse through the content.

divEle = soup.find(id = "articlebody")

Checking that a List is not empty in Hamcrest

Create your own custom IsEmpty TypeSafeMatcher:

Even if the generics problems are fixed in 1.3 the great thing about this method is it works on any class that has an isEmpty() method! Not just Collections!

For example it will work on String as well!

/* Matches any class that has an <code>isEmpty()</code> method
 * that returns a <code>boolean</code> */ 
public class IsEmpty<T> extends TypeSafeMatcher<T>
{
    @Factory
    public static <T> Matcher<T> empty()
    {
        return new IsEmpty<T>();
    }

    @Override
    protected boolean matchesSafely(@Nonnull final T item)
    {
        try { return (boolean) item.getClass().getMethod("isEmpty", (Class<?>[]) null).invoke(item); }
        catch (final NoSuchMethodException e) { return false; }
        catch (final InvocationTargetException | IllegalAccessException e) { throw new RuntimeException(e); }
    }

    @Override
    public void describeTo(@Nonnull final Description description) { description.appendText("is empty"); }
}

Get User's Current Location / Coordinates

Usage:

Define field in class

let getLocation = GetLocation()

Use in function of class by simple code:

getLocation.run {
    if let location = $0 {
        print("location = \(location.coordinate.latitude) \(location.coordinate.longitude)")
    } else {
        print("Get Location failed \(getLocation.didFailWithError)")
    }
}

Class:

import CoreLocation

public class GetLocation: NSObject, CLLocationManagerDelegate {
    let manager = CLLocationManager()
    var locationCallback: ((CLLocation?) -> Void)!
    var locationServicesEnabled = false
    var didFailWithError: Error?

    public func run(callback: @escaping (CLLocation?) -> Void) {
        locationCallback = callback
        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
        manager.requestWhenInUseAuthorization()
        locationServicesEnabled = CLLocationManager.locationServicesEnabled()
        if locationServicesEnabled { manager.startUpdatingLocation() }
        else { locationCallback(nil) }
    }

   public func locationManager(_ manager: CLLocationManager,
                         didUpdateLocations locations: [CLLocation]) {
        locationCallback(locations.last!)
        manager.stopUpdatingLocation()
    }

    public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        didFailWithError = error
        locationCallback(nil)
        manager.stopUpdatingLocation()
    }

    deinit {
        manager.stopUpdatingLocation()
    }
}


Don't forget to add the "NSLocationWhenInUseUsageDescription" in the info.plist.

Command-line Unix ASCII-based charting / plotting tool

Another simpler/lighter alternative to gnuplot is ervy, a NodeJS based terminal charts tool.

Supported types: scatter (XY points), bar, pie, bullet, donut and gauge.

Usage examples with various options can be found on the projects GitHub repo

enter image description here

enter image description here

Get a json via Http Request in NodeJS

Just setting json option to true, the body will contain the parsed json:

request({
  url: 'http://...',
  json: true
}, function(error, response, body) {
  console.log(body);
});

json_encode/json_decode - returns stdClass instead of Array in PHP

There is also a good PHP 4 json encode / decode library (that is even PHP 5 reverse compatible) written about in this blog post: Using json_encode() and json_decode() in PHP4 (Jun 2009).

The concrete code is by Michal Migurski and by Matt Knapp:

How to change Bootstrap's global default font size?

The recommended way to do this from the current v4 docs is:

$font-size-base: 0.8rem;
$line-height-base: 1;

Be sure to define the variables above the bootstrap css include and they will override the bootstrap.

No need for anything else and this is the cleanest way

It's described quite clearly in the docs https://getbootstrap.com/docs/4.1/content/typography/#global-settings

How to submit an HTML form without redirection

One-liner solution as of 2020, if your data is not meant to be sent as multipart/form-data or application/x-www-form-urlencoded:

<form onsubmit='return false'>
    <!-- ... -->           
</form>

Division in Python 2.7. and 3.3

"/" is integer division in python 2 so it is going to round to a whole number. If you would like a decimal returned, just change the type of one of the inputs to float:

float(20)/15 #1.33333333

How to unnest a nested list

itertools provides the chain function for that:

From http://docs.python.org/library/itertools.html#recipes:

def flatten(listOfLists):
    "Flatten one level of nesting"
    return chain.from_iterable(listOfLists)

Note that the result is an iterable, so you may need list(flatten(...)).

Creating a procedure in mySql with parameters

Its very easy to create procedure in Mysql. Here, in my example I am going to create a procedure which is responsible to fetch all data from student table according to supplied name.

DELIMITER //
CREATE PROCEDURE getStudentInfo(IN s_name VARCHAR(64))
BEGIN
SELECT * FROM student_database.student s where s.sname = s_name;
END//
DELIMITER;

In the above example ,database and table names are student_database and student respectively. Note: Instead of s_name, you can also pass @s_name as global variable.

How to call procedure? Well! its very easy, simply you can call procedure by hitting this command

$mysql> CAll getStudentInfo('pass_required_name');

enter image description here

Simple function to sort an array of objects

You can sort an array ([...]) with the .sort function:

var people = [
    {'name': 'a75', 'item1': false, 'item2': false},
    {'name': 'z32', 'item1': true,  'item2': false},
    {'name': 'e77', 'item1': false, 'item2': false},
];

var sorted = people.sort(function IHaveAName(a, b) { // non-anonymous as you ordered...
    return b.name < a.name ?  1 // if b should come earlier, push a to end
         : b.name > a.name ? -1 // if b should come later, push a to begin
         : 0;                   // a and b are equal
});

How can I add a column that doesn't allow nulls in a Postgresql database?

As others have observed, you must either create a nullable column or provide a DEFAULT value. If that isn't flexible enough (e.g. if you need the new value to be computed for each row individually somehow), you can use the fact that in PostgreSQL, all DDL commands can be executed inside a transaction:

BEGIN;
ALTER TABLE mytable ADD COLUMN mycolumn character varying(50);
UPDATE mytable SET mycolumn = timeofday();    -- Just a silly example
ALTER TABLE mytable ALTER COLUMN mycolumn SET NOT NULL;
COMMIT;

Passing multiple parameters to pool.map() function in Python

You could use a map function that allows multiple arguments, as does the fork of multiprocessing found in pathos.

>>> from pathos.multiprocessing import ProcessingPool as Pool
>>> 
>>> def add_and_subtract(x,y):
...   return x+y, x-y
... 
>>> res = Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))
>>> res
[(-5, 5), (-2, 6), (1, 7), (4, 8), (7, 9), (10, 10), (13, 11), (16, 12), (19, 13), (22, 14)]
>>> Pool().map(add_and_subtract, *zip(*res))
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

pathos enables you to easily nest hierarchical parallel maps with multiple inputs, so we can extend our example to demonstrate that.

>>> from pathos.multiprocessing import ThreadingPool as TPool
>>> 
>>> res = TPool().amap(add_and_subtract, *zip(*Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))))
>>> res.get()
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

Even more fun, is to build a nested function that we can pass into the Pool. This is possible because pathos uses dill, which can serialize almost anything in python.

>>> def build_fun_things(f, g):
...   def do_fun_things(x, y):
...     return f(x,y), g(x,y)
...   return do_fun_things
... 
>>> def add(x,y):
...   return x+y
... 
>>> def sub(x,y):
...   return x-y
... 
>>> neato = build_fun_things(add, sub)
>>> 
>>> res = TPool().imap(neato, *zip(*Pool().map(neato, range(0,20,2), range(-5,5,1))))
>>> list(res)
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

If you are not able to go outside of the standard library, however, you will have to do this another way. Your best bet in that case is to use multiprocessing.starmap as seen here: Python multiprocessing pool.map for multiple arguments (noted by @Roberto in the comments on the OP's post)

Get pathos here: https://github.com/uqfoundation

JSON date to Java date?

That DateTime format is actually ISO 8601 DateTime. JSON does not specify any particular format for dates/times. If you Google a bit, you will find plenty of implementations to parse it in Java.

Here's one

If you are open to using something other than Java's built-in Date/Time/Calendar classes, I would also suggest Joda Time. They offer (among many things) a ISODateTimeFormat to parse these kinds of strings.

How to add multiple jar files in classpath in linux

You use the -classpath argument. You can use either a relative or absolute path. What that means is you can use a path relative to your current directory, OR you can use an absolute path that starts at the root /.

Example:

bash$ java -classpath path/to/jar/file MyMainClass

In this example the main function is located in MyMainClass and would be included somewhere in the jar file.

For compiling you need to use javac

Example:

bash$ javac -classpath path/to/jar/file MyMainClass.java

You can also specify the classpath via the environment variable, follow this example:

bash$ export CLASSPATH="path/to/jar/file:path/tojar/file2"
bash$ javac MyMainClass.java

For any normally complex java project you should look for the ant script named build.xml

How do I get AWS_ACCESS_KEY_ID for Amazon?

  1. Go to: http://aws.amazon.com/
  2. Sign Up & create a new account (they'll give you the option for 1 year trial or similar)
  3. Go to your AWS account overview
  4. Account menu in the upper-right (has your name on it)
  5. sub-menu: Security Credentials

PHP Get Highest Value from Array

You need to use by ksort(array("a"=>1,"b"=>2,"c"=>4,"d"=>5)); for more info: http://www.w3schools.com/php/php_arrays_sort.asp

How to write inside a DIV box with javascript

_x000D_
_x000D_
document.getElementById('log').innerHTML += '<br>Some new content!';
_x000D_
<div id="log">initial content</div>
_x000D_
_x000D_
_x000D_

Set the location in iPhone Simulator

As of iOS 5, the simulator has a configurable location.

Under the Debug menu, the last entry is "Location"; this gives you a sub menu with:

  • None
  • Custom Location
  • Apple Stores
  • Apple
  • City Bicycle Ride
  • City Run
  • Freeway Drive

Custom Location lets you enter a Lat/Long value. Bicycle ride, City Run, and Freeway Drive are simulation of a moving location (in Cupertino, of course).

Of course, this does nothing to help with debugging for iOS 4 (or earlier); but it's a definite improvement!

How to check if number is divisible by a certain number?

package lecture3;

import java.util.Scanner;

public class divisibleBy2and5 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("Enter an integer number:");
        Scanner input = new Scanner(System.in);
        int x;
        x = input.nextInt();
         if (x % 2==0){
             System.out.println("The integer number you entered is divisible by 2");
         }
         else{
             System.out.println("The integer number you entered is not divisible by 2");
             if(x % 5==0){
                 System.out.println("The integer number you entered is divisible by 5");
             } 
             else{
                 System.out.println("The interger number you entered is not divisible by 5");
             }
        }

    }
}

INFO: No Spring WebApplicationInitializer types detected on classpath

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>          
    <configuration>
        <source>1.8</source>
        <target>1.8</target>
    </configuration>
 </plugin>

This is the important plugin that should be in pom.xml. I spent my two days debugging and researching. This was the solution. This is Apache plugin to tell maven to use the the given Compiler.

When restoring a backup, how do I disconnect all active connections?

Try this:

DECLARE UserCursor CURSOR LOCAL FAST_FORWARD FOR
SELECT
    spid
FROM
    master.dbo.sysprocesses
WHERE DB_NAME(dbid) = 'dbname'--replace the dbname with your database
DECLARE @spid SMALLINT
DECLARE @SQLCommand VARCHAR(300)
OPEN UserCursor
FETCH NEXT FROM UserCursor INTO
    @spid
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @SQLCommand = 'KILL ' + CAST(@spid AS VARCHAR)
    EXECUTE(@SQLCommand)
    FETCH NEXT FROM UserCursor INTO
        @spid
END
CLOSE UserCursor
DEALLOCATE UserCursor
GO

How can I solve a connection pool problem between ASP.NET and SQL Server?

Yet another reason happened in my case, because of using async/await, resulting in the same error message:

System.InvalidOperationException: 'Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.'

Just a quick overview of what happened (and how I resolved it), hopefully this will help others in the future:

Finding the cause

This all happened in an ASP.NET Core 3.1 web project with Dapper and SQL Server, but I do think it is independent of that very kind of project.

First, I have a central function to get me SQL connections:

internal async Task<DbConnection> GetConnection()
{
    var r = new SqlConnection(GetConnectionString());
    await r.OpenAsync().ConfigureAwait(false);
    return r;
}

I'm using this function in dozens of methods like e.g. this one:

public async Task<List<EmployeeDbModel>> GetAll()
{
    await using var conn = await GetConnection();
    var sql = @"SELECT * FROM Employee";

    var result = await conn.QueryAsync<EmployeeDbModel>(sql);
    return result.ToList();
}

As you can see, I'm using the new using statement without the curly braces ({, }), so disposal of the connection is done at the end of the function.

Still, I got the error about no more connections in the pool being available.

I started debugging my application and let it halt upon the exception happening. When it halted, I first did a look at the Call Stack window, but this only showed some location inside System.Data.SqlClient, and was no real help to me:

enter image description here

Next, I took a look at the Tasks window, which was of a much better help:

enter image description here

There were literally thousands of calls to my own GetConnection method in an "Awaiting" or "Scheduled" state.

When double-clicking such a line in the Tasks window, it showed me the related location in my code via the Call Stack window.

This helped my to find out the real reason of this behaviour. It was in the below code (just for completeness):

[Route(nameof(LoadEmployees))]
public async Task<IActionResult> LoadEmployees(
    DataSourceLoadOptions loadOption)
{
    var data = await CentralDbRepository.EmployeeRepository.GetAll();

    var list =
        data.Select(async d =>
            {
                var values = await CentralDbRepository.EmployeeRepository.GetAllValuesForEmployee(d);
                return await d.ConvertToListItemViewModel(
                    values,
                    Config,
                    CentralDbRepository);
            })
            .ToListAsync();
    return Json(DataSourceLoader.Load(await list, loadOption));
}

In the above controller action, I first did a call to EmployeeRepository.GetAll() to get a list of models from the database table "Employee".

Then, for each of the returned models (i.e. for each row of the result set), I did again do a database call to EmployeeRepository.GetAllValuesForEmployee(d).

While this is very bad in terms of performance anyway, in an async context it behaves in a way, that it is eating up connection pool connections without releasing them appropriately.

Solution

I resolved it by removing the SQL query in the inner loop of the outer SQL query.

This should be done by either completely omitting it, or if required, move it to one/multilpe JOINs in the outer SQL query to get all data from the database in one single SQL query.

tl;dr / lessons learned

Don't do lots of SQL queries in a short amount of time, especially when using async/await.

Carousel with Thumbnails in Bootstrap 3.0

  1. Use the carousel's indicators to display thumbnails.
  2. Position the thumbnails outside of the main carousel with CSS.
  3. Set the maximum height of the indicators to not be larger than the thumbnails.
  4. Whenever the carousel has slid, update the position of the indicators, positioning the active indicator in the middle of the indicators.

I'm using this on my site (for example here), but I'm using some extra stuff to do lazy loading, meaning extracting the code isn't as straightforward as I would like it to be for putting it in a fiddle.

Also, my templating engine is smarty, but I'm sure you get the idea.

The meat...

Updating the indicators:

<ol class="carousel-indicators">
    {assign var='walker' value=0}
    {foreach from=$item["imagearray"] key="key" item="value"}
        <li data-target="#myCarousel" data-slide-to="{$walker}"{if $walker == 0} class="active"{/if}>
            <img src='http://farm{$value["farm"]}.static.flickr.com/{$value["server"]}/{$value["id"]}_{$value["secret"]}_s.jpg'>
        </li>

        {assign var='walker' value=1 + $walker}
    {/foreach}
</ol>

Changing the CSS related to the indicators:

.carousel-indicators {
    bottom:-50px;
    height: 36px;
    overflow-x: hidden;
    white-space: nowrap;
}

.carousel-indicators li {
    text-indent: 0;
    width: 34px !important;
    height: 34px !important;
    border-radius: 0;
}

.carousel-indicators li img {
    width: 32px;
    height: 32px;
    opacity: 0.5;
}

.carousel-indicators li:hover img, .carousel-indicators li.active img {
    opacity: 1;
}

.carousel-indicators .active {
    border-color: #337ab7;
}

When the carousel has slid, update the list of thumbnails:

$('#myCarousel').on('slid.bs.carousel', function() {
    var widthEstimate = -1 * $(".carousel-indicators li:first").position().left + $(".carousel-indicators li:last").position().left + $(".carousel-indicators li:last").width(); 
    var newIndicatorPosition = $(".carousel-indicators li.active").position().left + $(".carousel-indicators li.active").width() / 2;
    var toScroll = newIndicatorPosition + indicatorPosition;
    var adjustedScroll = toScroll - ($(".carousel-indicators").width() / 2);
    if (adjustedScroll < 0)
        adjustedScroll = 0;

    if (adjustedScroll > widthEstimate - $(".carousel-indicators").width())
        adjustedScroll = widthEstimate - $(".carousel-indicators").width();

    $('.carousel-indicators').animate({ scrollLeft: adjustedScroll }, 800);

    indicatorPosition = adjustedScroll;
});

And, when your page loads, set the initial scroll position of the thumbnails:

var indicatorPosition = 0;

Correct way to initialize HashMap and can HashMap hold different value types?

It really depends on what kind of type safety you need. The non-generic way of doing it is best done as:

 Map x = new HashMap();

Note that x is typed as a Map. this makes it much easier to change implementations (to a TreeMap or a LinkedHashMap) in the future.

You can use generics to ensure a certain level of type safety:

Map<String, Object> x = new HashMap<String, Object>();

In Java 7 and later you can do

Map<String, Object> x = new HashMap<>();

The above, while more verbose, avoids compiler warnings. In this case the content of the HashMap can be any Object, so that can be Integer, int[], etc. which is what you are doing.

If you are still using Java 6, Guava Libraries (although it is easy enough to do yourself) has a method called newHashMap() which avoids the need to duplicate the generic typing information when you do a new. It infers the type from the variable declaration (this is a Java feature not available on constructors prior to Java 7).

By the way, when you add an int or other primitive, Java is autoboxing it. That means that the code is equivalent to:

 x.put("one", Integer.valueOf(1));

You can certainly put a HashMap as a value in another HashMap, but I think there are issues if you do it recursively (that is put the HashMap as a value in itself).

How to reduce the image file size using PIL

lets say you have a model called Book and on it a field called 'cover_pic', in that case, you can do the following to compress the image:

from PIL import Image
b = Book.objects.get(title='Into the wild')
image = Image.open(b.cover_pic.path)
image.save(b.image.path,quality=20,optimize=True)

hope it helps to anyone stumbling upon it.