Programs & Examples On #Freetext

FREETEXT is an SQL text-search predicate that uses stemming (e.g. -ing, -ly) and a thesaurus to search for the given string.

how to create and call scalar function in sql server 2008

Or you can simply use PRINT command instead of SELECT command. Try this,

PRINT dbo.fn_HomePageSlider(9, 3025)

Cannot use a CONTAINS or FREETEXT predicate on table or indexed view because it is not full-text indexed

  1. Make sure you have full-text search feature installed.

    Full-Text Search setup

  2. Create full-text search catalog.

     use AdventureWorks
     create fulltext catalog FullTextCatalog as default
    
     select *
     from sys.fulltext_catalogs
    
  3. Create full-text search index.

     create fulltext index on Production.ProductDescription(Description)
     key index PK_ProductDescription_ProductDescriptionID
    

    Before you create the index, make sure:
    - you don't already have full-text search index on the table as only one full-text search index allowed on a table
    - a unique index exists on the table. The index must be based on single-key column, that does not allow NULL.
    - full-text catalog exists. You have to specify full-text catalog name explicitly if there is no default full-text catalog.

You can do step 2 and 3 in SQL Sever Management Studio. In object explorer, right click on a table, select Full-Text index menu item and then Define Full-Text Index... sub-menu item. Full-Text indexing wizard will guide you through the process. It will also create a full-text search catalog for you if you don't have any yet.

enter image description here

You can find more info at MSDN

curl usage to get header

curl --head https://www.example.net

I was pointed to this by curl itself; when I issued the command with -X HEAD, it printed:

Warning: Setting custom HTTP method to HEAD with -X/--request may not work the 
Warning: way you want. Consider using -I/--head instead.

@Nullable annotation usage

It makes it clear that the method accepts null values, and that if you override the method, you should also accept null values.

It also serves as a hint for code analyzers like FindBugs. For example, if such a method dereferences its argument without checking for null first, FindBugs will emit a warning.

Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass

Go to Project>Build Path>Configure Build Path>Libraries>Remove Error libraries

After Refresh project and run again program.

mysql is not recognised as an internal or external command,operable program or batch

In my case, I resolved it by adding this path C:\xampp\mysql\bin to system variables path and then restarted pash/cmd.

Note: Click me if you don't know how to set the path and system variables.

How to use conditional statement within child attribute of a Flutter Widget (Center Widget)

****You can also use conditions by using this method** **

 int _moneyCounter = 0;
  void _rainMoney(){
    setState(() {
      _moneyCounter +=  100;
    });
  }

new Expanded(
          child: new Center(
            child: new Text('\$$_moneyCounter', 

            style:new TextStyle(
              color: _moneyCounter > 1000 ? Colors.blue : Colors.amberAccent,
              fontSize: 47,
              fontWeight: FontWeight.w800
            )

            ),
          ) 
        ),

For loop in Oracle SQL

You are pretty confused my friend. There are no LOOPS in SQL, only in PL/SQL. Here's a few examples based on existing Oracle table - copy/paste to see results:

-- Numeric FOR loop --
set serveroutput on -->> do not use in TOAD --
DECLARE
  k NUMBER:= 0;
BEGIN
  FOR i IN 1..10 LOOP
    k:= k+1;
    dbms_output.put_line(i||' '||k);
 END LOOP;
END;
/

-- Cursor FOR loop --
set serveroutput on
DECLARE
   CURSOR c1 IS SELECT * FROM scott.emp;
   i NUMBER:= 0;
BEGIN
  FOR e_rec IN c1 LOOP
  i:= i+1;
    dbms_output.put_line(i||chr(9)||e_rec.empno||chr(9)||e_rec.ename);
  END LOOP;
END;
/

-- SQL example to generate 10 rows --
SELECT 1 + LEVEL-1 idx
  FROM dual
CONNECT BY LEVEL <= 10
/

How do android screen coordinates work?

For Android API level 13 and you need to use this:

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int maxX = size.x; 
int maxY = size.y;

Then (0,0) is top left corner and (maxX,maxY) is bottom right corner of the screen.

The 'getWidth()' for screen size is deprecated since API 13

Furthermore getwidth() and getHeight() are methods of android.view.View class in android.So when your java class extends View class there is no windowManager overheads.

          int maxX=getwidht();
          int maxY=getHeight();

as simple as that.

Created Button Click Event c#

You need an event handler which will fire when the button is clicked. Here is a quick way -

  var button = new Button();
  button.Text = "my button";

  this.Controls.Add(button);

  button.Click += (sender, args) =>
                       {
                           MessageBox.Show("Some stuff");
                           Close();
                       };

But it would be better to understand a bit more about buttons, events, etc.

If you use the visual studio UI to create a button and double click the button in design mode, this will create your event and hook it up for you. You can then go to the designer code (the default will be Form1.Designer.cs) where you will find the event:

 this.button1.Click += new System.EventHandler(this.button1_Click);

You will also see a LOT of other information setup for the button, such as location, etc. - which will help you create one the way you want and will improve your understanding of creating UI elements. E.g. a default button gives this on my 2012 machine:

        this.button1.Location = new System.Drawing.Point(128, 214);
        this.button1.Name = "button1";
        this.button1.Size = new System.Drawing.Size(75, 23);
        this.button1.TabIndex = 1;
        this.button1.Text = "button1";
        this.button1.UseVisualStyleBackColor = true;

As for closing the Form, it is as easy as putting Close(); within your event handler:

private void button1_Click(object sender, EventArgs e)
    {
       MessageBox.Show("some text");
       Close();
    }

Reading Excel file using node.js

There are a few different libraries doing parsing of Excel files (.xlsx). I will list two projects I find interesting and worth looking into.

Node-xlsx

Excel parser and builder. It's kind of a wrapper for a popular project JS-XLSX, which is a pure javascript implementation from the Office Open XML spec.

node-xlsx project page

Example for parsing file

var xlsx = require('node-xlsx');

var obj = xlsx.parse(__dirname + '/myFile.xlsx'); // parses a file

var obj = xlsx.parse(fs.readFileSync(__dirname + '/myFile.xlsx')); // parses a buffer

ExcelJS

Read, manipulate and write spreadsheet data and styles to XLSX and JSON. It's an active project. At the time of writing the latest commit was 9 hours ago. I haven't tested this myself, but the api looks extensive with a lot of possibilites.

exceljs project page

Code example:

// read from a file
var workbook = new Excel.Workbook();
workbook.xlsx.readFile(filename)
    .then(function() {
        // use workbook
    });

// pipe from stream
var workbook = new Excel.Workbook();
stream.pipe(workbook.xlsx.createInputStream());

How can I remove an element from a list?

If you have a named list and want to remove a specific element you can try:

lst <- list(a = 1:4, b = 4:8, c = 8:10)

if("b" %in% names(lst)) lst <- lst[ - which(names(lst) == "b")]

This will make a list lst with elements a, b, c. The second line removes element b after it checks that it exists (to avoid the problem @hjv mentioned).

or better:

lst$b <- NULL

This way it is not a problem to try to delete a non-existent element (e.g. lst$g <- NULL)

com.android.build.transform.api.TransformException

I just had to Clean my project and then it built successfully afterwards.

How to dynamically create a class?

You can also dynamically create a class by using DynamicExpressions.

Since 'Dictionary's have compact initializers and handle key collisions, you will want to do something like this.

  var list = new Dictionary<string, string> {
    {
      "EmployeeID",
      "int"
    }, {
      "EmployeeName",
      "String"
    }, {
      "Birthday",
      "DateTime"
    }
  };

Or you might want to use a JSON converter to construct your serialized string object into something manageable.

Then using System.Linq.Dynamic;

  IEnumerable<DynamicProperty> props = list.Select(property => new DynamicProperty(property.Key, Type.GetType(property.Value))).ToList();

  Type t = DynamicExpression.CreateClass(props);

The rest is just using System.Reflection.

  object obj = Activator.CreateInstance(t);
  t.GetProperty("EmployeeID").SetValue(obj, 34, null);
  t.GetProperty("EmployeeName").SetValue(obj, "Albert", null);
  t.GetProperty("Birthday").SetValue(obj, new DateTime(1976, 3, 14), null);
}  

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 create a QR code reader in a HTML5 website?

Reader they show at http://www.webqr.com/index.html works like a charm, but literaly, you need the one on the webpage, the github version it's really hard to make it work, however, it is possible. The best way to go is reverse-engineer the example shown at the webpage.

However, to edit and get the full potential out of it, it's not so easy. At some point I may post the stripped-down reverse-engineered QR reader, but in the meantime have some fun hacking the code.

Happy coding.

How to make a JFrame Modal in Swing java

As far as I know, JFrame cannot do Modal mode. Use JDialog instead and call setModalityType(Dialog.ModalityType type) to set it to be modal (or not modal).

How to install cron

Cron is so named "deamon" (same as service under Win).

Most likely cron is already installed on your system (if it is a Linux/Unix system).

Look here: http://www.comptechdoc.org/os/linux/startupman/linux_sucron.html

or there http://en.wikipedia.org/wiki/Cron

for more details.

Check if returned value is not null and if so assign it, in one line, with one method call

Java lacks coalesce operator, so your code with an explicit temporary is your best choice for an assignment with a single call.

You can use the result variable as your temporary, like this:

dinner = ((dinner = cage.getChicken()) != null) ? dinner : getFreeRangeChicken();

This, however, is hard to read.

MongoDB: How to find the exact version of installed MongoDB

To check mongodb version use the mongod command with --version option.

To check MongoDB Server version, Open the command line via your terminal program and execute the following command:

Path : C:\Program Files\MongoDB\Server\3.2\bin Open Cmd and execute the following command: mongod --version To Check MongoDB Shell version, Type:

mongo --version

Reading CSV file and storing values into an array

LINQ way:

var lines = File.ReadAllLines("test.txt").Select(a => a.Split(';'));
var csv = from line in lines
          select (from piece in line
                  select piece);

^^Wrong - Edit by Nick

It appears the original answerer was attempting to populate csv with a 2 dimensional array - an array containing arrays. Each item in the first array contains an array representing that line number with each item in the nested array containing the data for that specific column.

var csv = from line in lines
          select (line.Split(',')).ToArray();

Lua string to int

I would recomend to check Hyperpolyglot, has an awesome comparison: http://hyperpolyglot.org/

http://hyperpolyglot.org/more#str-to-num-note

ps. Actually Lua converts into doubles not into ints.

The number type represents real (double-precision floating-point) numbers.

http://www.lua.org/pil/2.3.html

How to fix the "java.security.cert.CertificateException: No subject alternative names present" error?

I fixed this issue in a right way by adding the subject alt names in certificate rather than making any changes in code or disabling SSL unlike what other answers suggest here. If you see clearly the exception says the "Subject alt names are missing" so the right way should be to add them

Please look at this link to understand step by step.

The above error means that your JKS file is missing the required domain on which you are trying to access the application.You will need to Use Open SSL and the key tool to add multiple domains

  1. Copy the openssl.cnf into a current directory
  2. echo '[ subject_alt_name ]' >> openssl.cnf
  3. echo 'subjectAltName = DNS:example.mydomain1.com, DNS:example.mydomain2.com, DNS:example.mydomain3.com, DNS: localhost'>> openssl.cnf
  4. openssl req -x509 -nodes -newkey rsa:2048 -config openssl.cnf -extensions subject_alt_name -keyout private.key -out self-signed.pem -subj '/C=gb/ST=edinburgh/L=edinburgh/O=mygroup/OU=servicing/CN=www.example.com/[email protected]' -days 365
  5. Export the public key (.pem) file to PKS12 format. This will prompt you for password

    openssl pkcs12 -export -keypbe PBE-SHA1-3DES -certpbe PBE-SHA1-3DES -export -in
    self-signed.pem -inkey private.key -name myalias -out keystore.p12
    
  6. Create a.JKS from self-signed PEM (Keystore)

    keytool -importkeystore -destkeystore keystore.jks -deststoretype PKCS12 -srcstoretype PKCS12 -srckeystore keystore.p12
    
  7. Generate a Certificate from above Keystore or JKS file

    keytool -export -keystore keystore.jks -alias myalias -file selfsigned.crt
    
  8. Since the above certificate is Self Signed and is not validated by CA, it needs to be added in Truststore(Cacerts file in below location for MAC, for Windows, find out where your JDK is installed.)

    sudo keytool -importcert -file selfsigned.crt -alias myalias -keystore /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home/jre/lib/security/cacerts
    

Original answer posted on this link here.

How do you install Boost on MacOS?

In order to avoid troubles compiling third party libraries that need boost installed in your system, run this:

sudo port install boost +universal

Replace one character with another in Bash

Use parameter substitution:

string=${string// /.}

Concatenate strings from several rows using Pandas groupby

we can groupby the 'name' and 'month' columns, then call agg() functions of Panda’s DataFrame objects.

The aggregation functionality provided by the agg() function allows multiple statistics to be calculated per group in one calculation.

df.groupby(['name', 'month'], as_index = False).agg({'text': ' '.join})

enter image description here

How to avoid mysql 'Deadlock found when trying to get lock; try restarting transaction'

Deadlock happen when two transactions wait on each other to acquire a lock. Example:

  • Tx 1: lock A, then B
  • Tx 2: lock B, then A

There are numerous questions and answers about deadlocks. Each time you insert/update/or delete a row, a lock is acquired. To avoid deadlock, you must then make sure that concurrent transactions don't update row in an order that could result in a deadlock. Generally speaking, try to acquire lock always in the same order even in different transaction (e.g. always table A first, then table B).

Another reason for deadlock in database can be missing indexes. When a row is inserted/update/delete, the database needs to check the relational constraints, that is, make sure the relations are consistent. To do so, the database needs to check the foreign keys in the related tables. It might result in other lock being acquired than the row that is modified. Be sure then to always have index on the foreign keys (and of course primary keys), otherwise it could result in a table lock instead of a row lock. If table lock happen, the lock contention is higher and the likelihood of deadlock increases.

Print all properties of a Python Class

Just try beeprint

it prints something like this:

instance(Animal):
    legs: 2,
    name: 'Dog',
    color: 'Spotted',
    smell: 'Alot',
    age: 10,
    kids: 0,

I think is exactly what you need.

Why should I use a pointer rather than the object itself?

Well the main question is Why should I use a pointer rather than the object itself? And my answer, you should (almost) never use pointer instead of object, because C++ has references, it is safer then pointers and guarantees the same performance as pointers.

Another thing you mentioned in your question:

Object *myObject = new Object;

How does it work? It creates pointer of Object type, allocates memory to fit one object and calls default constructor, sounds good, right? But actually it isn't so good, if you dynamically allocated memory (used keyword new), you also have to free memory manually, that means in code you should have:

delete myObject;

This calls destructor and frees memory, looks easy, however in big projects may be difficult to detect if one thread freed memory or not, but for that purpose you can try shared pointers, these slightly decreases performance, but it is much easier to work with them.


And now some introduction is over and go back to question.

You can use pointers instead of objects to get better performance while transferring data between function.

Take a look, you have std::string (it is also object) and it contains really much data, for example big XML, now you need to parse it, but for that you have function void foo(...) which can be declarated in different ways:

  1. void foo(std::string xml); In this case you will copy all data from your variable to function stack, it takes some time, so your performance will be low.
  2. void foo(std::string* xml); In this case you will pass pointer to object, same speed as passing size_t variable, however this declaration has error prone, because you can pass NULL pointer or invalid pointer. Pointers usually used in C because it doesn't have references.
  3. void foo(std::string& xml); Here you pass reference, basically it is the same as passing pointer, but compiler does some stuff and you cannot pass invalid reference (actually it is possible to create situation with invalid reference, but it is tricking compiler).
  4. void foo(const std::string* xml); Here is the same as second, just pointer value cannot be changed.
  5. void foo(const std::string& xml); Here is the same as third, but object value cannot be changed.

What more I want to mention, you can use these 5 ways to pass data no matter which allocation way you have chosen (with new or regular).


Another thing to mention, when you create object in regular way, you allocate memory in stack, but while you create it with new you allocate heap. It is much faster to allocate stack, but it is kind a small for really big arrays of data, so if you need big object you should use heap, because you may get stack overflow, but usually this issue is solved using STL containers and remember std::string is also container, some guys forgot it :)

Regular Expressions- Match Anything

Use .*, and make sure you are using your implementations' equivalent of single-line so you will match on line endings.

There is a great explanation here -> http://www.regular-expressions.info/dot.html

how to overwrite css style

Increase your CSS Specificity

Example:

.parent-class .flex-control-thumbs li {
  width: auto;
  float: none;
}

Demo:

_x000D_
_x000D_
.sample-class {
  height: 50px;
  width: 50px;
  background: red;
}

.inner-page .sample-class {
  background: green;
}
_x000D_
<div>
  <div class="sample-class"></div>
</div>

<div class="inner-page">
  <div class="sample-class"></div>
</div>
_x000D_
_x000D_
_x000D_

add to array if it isn't there already

Easy to write, but not the most effective one:

$array = array_unique(array_merge($array, $array_to_append));

This one is probably faster:

$array = array_merge($array, array_diff($array_to_append, $array));

Bootstrap modal - close modal when "call to action" button is clicked

Make as shown.

_x000D_
_x000D_
  $(document).ready(function(){_x000D_
    $('#myModal').modal('show');_x000D_
_x000D_
    $('#myBtn').on('click', function(){_x000D_
      $('#myModal').modal('show');_x000D_
    });_x000D_
    _x000D_
  });_x000D_
<br/>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
  <title>Bootstrap Example</title>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
  <h2>Activate Modal with JavaScript</h2>_x000D_
  <!-- Trigger the modal with a button -->_x000D_
  <button type="button" class="btn btn-info btn-lg" id="myBtn">Open Modal</button>_x000D_
_x000D_
  <!-- Modal -->_x000D_
  <div class="modal fade" id="myModal" role="dialog">_x000D_
    <div class="modal-dialog">_x000D_
    _x000D_
      <!-- Modal content-->_x000D_
      <div class="modal-content">_x000D_
        <div class="modal-header">_x000D_
          <button type="button" class="close" data-dismiss="modal">&times;</button>_x000D_
          <h4 class="modal-title">Modal Header</h4>_x000D_
        </div>_x000D_
        <div class="modal-body">_x000D_
          <p>Some text in the modal.</p>_x000D_
        </div>_x000D_
_x000D_
      </div>_x000D_
      _x000D_
    </div>_x000D_
  </div>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

Why do people use Heroku when AWS is present? What distinguishes Heroku from AWS?

There are a lot of different ways to look at this decision from development, IT, and business objectives, so don't feel bad if it seems overwhelming. But also - don't overthink scalability.

Think about your requirements.

I've engineered websites which have serviced over 8M uniques a day and delivered terabytes of video a week built on infrastructures starting at $250k in capital hardware unr by a huge $MM IT labor staff.

But I've also had smaller websites which were designed to generate $10-$20k per year, didn't have very high traffic, db or processing requirements, and I ran those off a $10/mo generic hosting account without compromise.

In the future, deployment will look more like Heroku than AWS, just because of progress. There is zero value in the IT knob-turning of scaling internet infrastructures which isn't increasingly automatable, and none of it has anything to do with the value of the product or service you are offering.

Also, keep in mind with a commercial website - scalability is what we often call a 'good problem to have' - although scalability issues with sites like Facebook and Twitter were very high-profile, they had zero negative effect on their success - the news might have even contributed to more signups (all press is good press).

If you have a service which is generating a 100k+ uniques a day and having scaling issues, I'd be glad to take it off your hands for you no matter what the language, db, platform, or infrastructure you are running on!

Scalability is a fixable implementation problem - not having customers is an existential issue.

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

Any chance your IIS is configured to require SSL on connections to your site/application?

React Native absolute positioning horizontal centre

It's very simple really. Use percentage for width and left properties. For example:

logo : {
  position: 'absolute',
  top : 50,
  left: '30%',
  zIndex: 1,
  width: '40%',
  height: 150,
}

Whatever width is, left equals (100% - width)/2

Java Read Large Text File With 70million line of text

This article is a great way to start.

Also, you need to create test cases in which you read first 10k(or something else, but shouldn't be too small) lines and calculate the reading times accordingly.

Threading might be a good way to go, but it's important that we know what you will be doing with the data.

Another thing to be considered is, how you will store that size of data.

Input jQuery get old value before onchange and get value after on change

Definitely you will need to store old value manually, depending on what moment you are interested (before focusing, from last change). Initial value can be taken from defaultValue property:

function onChange() {
    var oldValue = this.defaultValue;
    var newValue = this.value;
}

Value before focusing can be taken as shown in Gone Coding's answer. But you have to keep in mind that value can be changed without focusing.

how to check the dtype of a column in python pandas

You can access the data-type of a column with dtype:

for y in agg.columns:
    if(agg[y].dtype == np.float64 or agg[y].dtype == np.int64):
          treat_numeric(agg[y])
    else:
          treat_str(agg[y])

MySQL SELECT only not null values

Yes use NOT NULL in your query like this below.

SELECT * 
FROM table
WHERE col IS NOT NULL;

Why maven? What are the benefits?

Maven can be considered as complete project development tool not just build tool like Ant. You should use Eclipse IDE with maven plugin to fix all your problems.

Here are few advantages of Maven, quoted from the Benefits of using Maven page:

Henning

  • quick project setup, no complicated build.xml files, just a POM and go
  • all developers in a project use the same jar dependencies due to centralized POM.
  • getting a number of reports and metrics for a project "for free"
  • reduce the size of source distributions, because jars can be pulled from a central location

Emmanuel Venisse

  • a lot of goals are available so it isn't necessary to develop some specific build process part contrary to ANT we can reuse existing ANT tasks in build process with antrun plugin

Jesse Mcconnell

  • Promotes modular design of code. by making it simple to manage mulitple projects it allows the design to be laid out into muliple logical parts, weaving these parts together through the use of dependency tracking in pom files.
  • Enforces modular design of code. it is easy to pay lipservice to modular code, but when the code is in seperate compiling projects it is impossible to cross pollinate references between modules of code unless you specifically allow for it in your dependency management... there is no 'I'll just do this now and fix it later' implementations.
  • Dependency Management is clearly declared. with the dependency management mechanism you have to try to screw up your jar versioning...there is none of the classic problem of 'which version of this vendor jar is this?' And setting it up on an existing project rips the top off of the existing mess if it exists when you are forced to make 'unknown' versions in your repository to get things up and running...that or lie to yourself that you know the actual version of ABC.jar.
  • strong typed life cycle there is a strong defined lifecycle that a software system goes thru from the initiation of a build to the end... and the users are allowed to mix and match their system to the lifecycle instead of cobble together their own lifecycle.. this has the additional benefit of allowing people to move from one project to another and speak using the same vocabulary in terms of software building

Vincent Massol

  • Greater momentum: Ant is now legacy and not moving fast ahead. Maven is forging ahead fast and there's a potential of having lots of high-value tools around Maven (CI, Dashboard project, IDE integration, etc).

DB2 Timestamp select statement

@bhamby is correct. By leaving the microseconds off of your timestamp value, your query would only match on a usagetime of 2012-09-03 08:03:06.000000

If you don't have the complete timestamp value captured from a previous query, you can specify a ranged predicate that will match on any microsecond value for that time:

...WHERE id = 1 AND usagetime BETWEEN '2012-09-03 08:03:06' AND '2012-09-03 08:03:07'

or

...WHERE id = 1 AND usagetime >= '2012-09-03 08:03:06' 
   AND usagetime < '2012-09-03 08:03:07'

Bootstrap - Removing padding or margin when screen size is smaller

In Bootstrap 4, the 15px margin the initial container has, cascades down to all rows and columns. So, something like this works for me...

@media (max-width: 576px) {
    .container-fluid {
        padding-left: 5px;
        padding-right: 5px;
    }

    .row {
        margin-left: -5px;
        margin-right: -5px;
    }
    .col, .col-1, .col-10, .col-11, .col-12, .col-2, .col-3, .col-4, .col-5, .col-6, .col-7, .col-8, .col-9, .col-auto, .col-lg, .col-lg-1, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-auto, .col-md, .col-md-1, .col-md-10, .col-md-11, .col-md-12, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-auto, .col-sm, .col-sm-1, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-auto, .col-xl, .col-xl-1, .col-xl-10, .col-xl-11, .col-xl-12, .col-xl-2, .col-xl-3, .col-xl-4, .col-xl-5, .col-xl-6, .col-xl-7, .col-xl-8, .col-xl-9, .col-xl-auto {
        padding-left: 5px;
        padding-right: 5px;
    }
    .row.no-gutters {
        margin-left: 0;
        margin-right: 0;
    }
}

Add more than one parameter in Twig path

Consider making your route:

_files_manage:
    pattern: /files/management/{project}/{user}
    defaults: { _controller: AcmeTestBundle:File:manage }

since they are required fields. It will make your url's prettier, and be a bit easier to manage.

Your Controller would then look like

 public function projectAction($project, $user)

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

Try below code,

$cookieFile = "cookies.txt";
if(!file_exists($cookieFile)) {
    $fh = fopen($cookieFile, "w");
    fwrite($fh, "");
    fclose($fh);
}


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiCall);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_VERBOSE, true);
if(!curl_exec($ch)){
    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}
else{
    $response = curl_exec($ch); 
}
curl_close($ch);
$result = json_decode($response, true);

echo '<pre>';
var_dump($result);
echo'</pre>';

I hope this will help you.

Best regards, Dasitha.

Javascript: Extend a Function

2017+ solution

The idea of function extensions comes from functional paradigm, which is natively supported since ES6:

function init(){
    doSomething();
}

// extend.js

init = (f => u => { f(u)
    doSomethingHereToo();
})(init);

init();

As per @TJCrowder's concern about stack dump, the browsers handle the situation much better today. If you save this code into test.html and run it, you get

test.html:3 Uncaught ReferenceError: doSomething is not defined
    at init (test.html:3)
    at test.html:8
    at test.html:12

Line 12: the init call, Line 8: the init extension, Line 3: the undefined doSomething() call.

Note: Much respect to veteran T.J. Crowder, who kindly answered my question many years ago, when I was a newbie. After the years, I still remember the respectfull attitude and I try to follow the good example.

Java - Abstract class to contain variables?

Of course. The whole idea of abstract classes is that they can contain some behaviour or data which you require all sub-classes to contain. Think of the simple example of WheeledVehicle - it should have a numWheels member variable. You want all sub classes to have this variable. Remember that abstract classes are a very useful feature when developing APIs, as they can ensure that people who extend your API won't break it.

Input button target="_blank" isn't causing the link to load in a new window/tab

use formtarget="_blank" its working for me

<input type="button" onClick="parent.location='http://www.facebook.com/'" value="facebook" formtarget="_blank">

Browser compatibility: from caniuse.com
IE: 10+ | Edge: 12+ | Firefox: 4+ | Chrome: 15+ | Safari/iOS: 5.1+ | Android: 4+

Create a new Ruby on Rails application using MySQL instead of SQLite

$ rails --help 

is always your best friend

usage:

$ rails new APP_PATH[options]

also note that options should be given after the application name

rails and mysql

$ rails new project_name -d mysql

rails and postgresql

$ rails new project_name -d postgresql

DateTime.TryParse issue with dates of yyyy-dd-MM format

From DateTime on msdn:

Type: System.DateTime% When this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. The conversion fails if the s parameter is null, is an empty string (""), or does not contain a valid string representation of a date and time. This parameter is passed uninitialized.

Use parseexact with the format string "yyyy-dd-MM hh:mm tt" instead.

Making button go full-width?

Bootstrap / CSS

Use col-12, btn-block, w-100, form-control or width:100%

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>

         <button class="btn btn-success col-12">
             class="col-12"
         </button>
    
         <button class="btn btn-primary w-100">
             class="w-100"
         </button>

         <button class="btn btn-secondary btn-block">
             class="btn-block"
         </button>
         
         <button class="btn btn-success form-control">
             class="form-control"
         </button>
         
         <button class="btn btn-danger" style="width:100%">
             style="width:100%"
         </button>
_x000D_
_x000D_
_x000D_

How to get config parameters in Symfony2 Twig Templates

You can simply bind $this->getParameter('app.version') in controller to twig param and then render it.

Eclipse and Windows newlines

As mentioned here and here:

Set file encoding to UTF-8 and line-endings for new files to Unix, so that text files are saved in a format that is not specific to the Windows OS and most easily shared across heterogeneous developer desktops:

  • Navigate to the Workspace preferences (General:Workspace)
  • Change the Text File Encoding to UTF-8
  • Change the New Text File Line Delimiter to Other and choose Unix from the pick-list

alt text

  • Note: to convert the line endings of an existing file, open the file in Eclipse and choose File : Convert Line Delimiters to : Unix

Tip: You can easily convert existing file by selecting then in the Package Explorer, and then going to the menu entry File : Convert Line Delimiters to : Unix

Does an HTTP Status code of 0 have any meaning?

Since iOS 9, you need to add "App Transport Security Settings" to your info.plist file and allow "Allow Arbitrary Loads" before making request to non-secure HTTP web service. I had this issue in one of my app.

What do \t and \b do?

This behaviour is terminal-specific and specified by the terminal emulator you use (e.g. xterm) and the semantics of terminal that it provides. The terminal behaviour has been very stable for the last 20 years, and you can reasonably rely on the semantics of \b.

The application has stopped unexpectedly: How to Debug?

Filter your log to just Error and look for FATAL EXCEPTION

Html.fromHtml deprecated in Android N

Or you can use androidx.core.text.HtmlCompat:

HtmlCompat.fromHtml("<b>HTML</b>", HtmlCompat.FROM_HTML_MODE_LEGACY)

HtmlCompat docs

Extracting numbers from vectors of strings

Or simply:

as.numeric(gsub("\\D", "", years))
# [1] 20  1

Iterator invalidation rules

C++11 (Source: Iterator Invalidation Rules (C++0x))


Insertion

Sequence containers

  • vector: all iterators and references before the point of insertion are unaffected, unless the new container size is greater than the previous capacity (in which case all iterators and references are invalidated) [23.3.6.5/1]
  • deque: all iterators and references are invalidated, unless the inserted member is at an end (front or back) of the deque (in which case all iterators are invalidated, but references to elements are unaffected) [23.3.3.4/1]
  • list: all iterators and references unaffected [23.3.5.4/1]
  • forward_list: all iterators and references unaffected (applies to insert_after) [23.3.4.5/1]
  • array: (n/a)

Associative containers

  • [multi]{set,map}: all iterators and references unaffected [23.2.4/9]

Unsorted associative containers

  • unordered_[multi]{set,map}: all iterators invalidated when rehashing occurs, but references unaffected [23.2.5/8]. Rehashing does not occur if the insertion does not cause the container's size to exceed z * B where z is the maximum load factor and B the current number of buckets. [23.2.5/14]

Container adaptors

  • stack: inherited from underlying container
  • queue: inherited from underlying container
  • priority_queue: inherited from underlying container

Erasure

Sequence containers

  • vector: every iterator and reference at or after the point of erase is invalidated [23.3.6.5/3]
  • deque: erasing the last element invalidates only iterators and references to the erased elements and the past-the-end iterator; erasing the first element invalidates only iterators and references to the erased elements; erasing any other elements invalidates all iterators and references (including the past-the-end iterator) [23.3.3.4/4]
  • list: only the iterators and references to the erased element is invalidated [23.3.5.4/3]
  • forward_list: only the iterators and references to the erased element is invalidated (applies to erase_after) [23.3.4.5/1]
  • array: (n/a)

Associative containers

  • [multi]{set,map}: only iterators and references to the erased elements are invalidated [23.2.4/9]

Unordered associative containers

  • unordered_[multi]{set,map}: only iterators and references to the erased elements are invalidated [23.2.5/13]

Container adaptors

  • stack: inherited from underlying container
  • queue: inherited from underlying container
  • priority_queue: inherited from underlying container

Resizing

  • vector: as per insert/erase [23.3.6.5/12]
  • deque: as per insert/erase [23.3.3.3/3]
  • list: as per insert/erase [23.3.5.3/1]
  • forward_list: as per insert/erase [23.3.4.5/25]
  • array: (n/a)

Note 1

Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container. [23.2.1/11]

Note 2

no swap() function invalidates any references, pointers, or iterators referring to the elements of the containers being swapped. [ Note: The end() iterator does not refer to any element, so it may be invalidated. —end note ] [23.2.1/10]

Note 3

Other than the above caveat regarding swap(), it's not clear whether "end" iterators are subject to the above listed per-container rules; you should assume, anyway, that they are.

Note 4

vector and all unordered associative containers support reserve(n) which guarantees that no automatic resizing will occur at least until the size of the container grows to n. Caution should be taken with unordered associative containers because a future proposal will allow the specification of a minimum load factor, which would allow rehashing to occur on insert after enough erase operations reduce the container size below the minimum; the guarantee should be considered potentially void after an erase.

What does Maven do, in theory and in practice? When is it worth to use it?

From the Sonatype doc:

The answer to this question depends on your own perspective. The great majority of Maven users are going to call Maven a “build tool”: a tool used to build deployable artifacts from source code. Build engineers and project managers might refer to Maven as something more comprehensive: a project management tool. What is the difference? A build tool such as Ant is focused solely on preprocessing, compilation, packaging, testing, and distribution. A project management tool such as Maven provides a superset of features found in a build tool. In addition to providing build capabilities, Maven can also run reports, generate a web site, and facilitate communication among members of a working team.

I'd strongly recommend looking at the Sonatype doc and spending some time looking at the available plugins to understand the power of Maven.

Very briefly, it operates at a higher conceptual level than (say) Ant. With Ant, you'd specify the set of files and resources that you want to build, then specify how you want them jarred together, and specify the order that should occur in (clean/compile/jar). With Maven this is all implicit. Maven expects to find your files in particular places, and will work automatically with that. Consequently setting up a project with Maven can be a lot simpler, but you have to play by Maven's rules!

How to convert date to timestamp in PHP?

Using strtotime() function you can easily convert date to timestamp

<?php
// set default timezone
date_default_timezone_set('America/Los_Angeles');

//define date and time
$date = date("d M Y H:i:s");

// output
echo strtotime($date);
?> 

More info: http://php.net/manual/en/function.strtotime.php

Online conversion tool: http://freeonlinetools24.com/

How to add a Try/Catch to SQL Stored Procedure

yep - you can even nest the try catch statements as:

BEGIN TRY
SET @myFixDte = CONVERT(datetime, @myFixDteStr,101)
END TRY
BEGIN CATCH
    BEGIN TRY
        SET @myFixDte = CONVERT(datetime, @myFixDteStr,103)
END TRY
BEGIN CATCH
    BEGIN TRY
        SET @myFixDte = CONVERT(datetime, @myFixDteStr,104)
    END TRY
    BEGIN CATCH
        SET @myFixDte = CONVERT(datetime, @myFixDteStr,105)
    END CATCH
END CATCH END CATCH

Where does Git store files?

I also couldn't find my git repository. I am using Windows 8 and created my repository (by mistake) under C:\Program Files (x86)\Git. I could see the repository folder in bash but not in cmd or Windows Explorer.

Then I remembered about Windows's "Virtual Store" feature. My repository folder was actually created under C:\Users\<username>\AppData\Local\VirtualStore\Program Files (x86)\Git\<myrepo> and in there was my .git folder!

Angular 2 select option (dropdown) - how to get the value on change so it can be used in a function?

Another solution would be,you can get the object itself as value if you are not mentioning it's id as value: Note: [value] and [ngValue] both works here.

<select (change)="your_method(values[$event.target.selectedIndex])">
  <option *ngFor="let v of values" [value]="v" >  
    {{v.name}}
  </option>
</select>

In ts:

your_method(v:any){
  //access values here as needed. 
  // v.id or v.name
}

Note: If you are using reactive form and you want to catch selected value on form Submit, you should use [ngValue] directive instead of [value] in above scanerio

Example:

  <select (change)="your_method(values[$event.target.selectedIndex])" formControlName="form_control_name">
      <option *ngFor="let v of values" [ngValue]="v" >  
        {{v.name}}
      </option>
    </select>

In ts:

form_submit_method(){
        let v : any = this.form_group_name.value.form_control_name;  
    }

convert:not authorized `aaaa` @ error/constitute.c/ReadImage/453

I use many times the ImageMagic convert command to convert *.tif files to *.pdf files.

I don't know why but today I began to receive the following error:

convert: not authorized `a.pdf' @ error/constitute.c/WriteImage/1028.

After issuing the command:

convert a.tif a.pdf

After reading the above answers I edited the file /etc/ImageMagick-6/policy.xml

and changed the line:

policy domain="coder" rights="none" pattern="PDF" 

to

policy domain="coder" rights="read|write" pattern="PDF"

and now everything works fine.

I have "ImageMagick 6.8.9-9 Q16 x86_64 2018-09-28" on "Ubuntu 16.04.5 LTS".

How to create a Jar file in Netbeans

I also tried to make an executable jar file that I could run with the following command:

java -jar <jarfile>

After some searching I found the following link:

Packaging and Deploying Desktop Java Applications

I set the project's main class:

  1. Right-click the project's node and choose Properties
  2. Select the Run panel and enter the main class in the Main Class field
  3. Click OK to close the Project Properties dialog box
  4. Clean and build project

Then in the fodler dist the newly created jar should be executable with the command I mentioned above.

How to make an embedded video not autoplay

Try replacing your movie param line with

<param name="movie" value="untitled_skin.swf&autoStart=false">

Using NOT operator in IF conditions

It really depends on what you're trying to accomplish. If you have no else clause then if(!doSomething()) seems fine. However, if you have

if(!doSomething()) {
    ...
}
else {
    // do something else
}

I'd probably reverse that logic to remove the ! operator and make the if clause slightly more clear.

Current time formatting with Javascript

There are many great libraries out there, for those interested

There really shouldn't be a need these days to invent your own formatting specifiers.

Is there "\n" equivalent in VBscript?

This page has a table of string constants including vbCrLf

vbCrLf | Chr(13) & Chr(10) | Carriage return–linefeed combination

Check if a folder exist in a directory and create them using C#

    String path = Server.MapPath("~/MP_Upload/");
    if (!Directory.Exists(path))
    {
        Directory.CreateDirectory(path);
    }

How to draw an empty plot?

You need a new plot window, and also a coordinate system, so you need plot.new() and plot.window(), then you can start to add graph elements:

plot.new( )
plot.window( xlim=c(-5,5), ylim=c(-5,5) )

points( rnorm(100), rnorm(100) )
axis( side=1 )

example plot

Resize a large bitmap file to scaled output file on Android

There is a great article about this exact issue on the Android developer website: Loading Large Bitmaps Efficiently

How to enable LogCat/Console in Eclipse for Android?

In the "Window" menu, open "Open Perspective" -> "Debug".

alt text click On the plus image icon(you see the below image at status bar), and then select "Logcat"....

android: how to use getApplication and getApplicationContext from non activity / service class

Either pass in a Context (so you can access resources), or make the helper methods static.

cmake error 'the source does not appear to contain CMakeLists.txt'

Since you add .. after cmake, it will jump up and up (just like cd ..) in the directory. But if you want to run cmake under the same folder with CMakeLists.txt, please use . instead of ...

How do I get only directories using Get-ChildItem?

Use:

Get-ChildItem \\myserver\myshare\myshare\ -Directory | Select-Object -Property name |  convertto-csv -NoTypeInformation  | Out-File c:\temp\mydirectorylist.csv

Which does the following

  • Get a list of directories in the target location: Get-ChildItem \\myserver\myshare\myshare\ -Directory
  • Extract only the name of the directories: Select-Object -Property name
  • Convert the output to CSV format: convertto-csv -NoTypeInformation
  • Save the result to a file: Out-File c:\temp\mydirectorylist.csv

Splitting strings using a delimiter in python

So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:

>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"

Indirectly referenced from required .class file

I was getting this error:

The type com.ibm.portal.state.exceptions.StateException cannot be resolved. It is indirectly referenced from required .class files

Doing the following fixed it for me:

Properties -> Java build path -> Libraries -> Server Library[wps.base.v61]unbound -> Websphere Portal v6.1 on WAS 7 -> Finish -> OK

How to get current CPU and RAM usage in Python?

You can use psutil or psmem with subprocess example code

import subprocess
cmd =   subprocess.Popen(['sudo','./ps_mem'],stdout=subprocess.PIPE,stderr=subprocess.PIPE) 
out,error = cmd.communicate() 
memory = out.splitlines()

Reference http://techarena51.com/index.php/how-to-install-python-3-and-flask-on-linux/

https://github.com/Leo-g/python-flask-cmd

Quick unix command to display specific lines in the middle of a file?

What about:

tail -n +347340107 filename | head -n 100

I didn't test it, but I think that would work.

Access Session attribute on jstl

You don't need the jsp:useBean to set the model if you already have a controller which prepared the model.

Just access it plain by EL:

<p>${Questions.questionPaperID}</p>
<p>${Questions.question}</p>

or by JSTL <c:out> tag if you'd like to HTML-escape the values or when you're still working on legacy Servlet 2.3 containers or older when EL wasn't supported in template text yet:

<p><c:out value="${Questions.questionPaperID}" /></p>
<p><c:out value="${Questions.question}" /></p>

See also:


Unrelated to the problem, the normal practice is by the way to start attribute name with a lowercase, like you do with normal variable names.

session.setAttribute("questions", questions);

and alter EL accordingly to use ${questions}.

Also note that you don't have any JSTL tag in your code. It's all plain JSP.

Convert a Map<String, String> to a POJO

@Hamedz if use many data, use Jackson to convert light data, use apache... TestCase:

import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; import org.apache.commons.beanutils.BeanUtils; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; public class TestPerf { public static final int LOOP_MAX_COUNT = 1000; public static void main(String[] args) { Map<String, Object> map = new HashMap<>(); map.put("success", true); map.put("number", 1000); map.put("longer", 1000L); map.put("doubler", 1000D); map.put("data1", "testString"); map.put("data2", "testString"); map.put("data3", "testString"); map.put("data4", "testString"); map.put("data5", "testString"); map.put("data6", "testString"); map.put("data7", "testString"); map.put("data8", "testString"); map.put("data9", "testString"); map.put("data10", "testString"); runBeanUtilsPopulate(map); runJacksonMapper(map); } private static void runBeanUtilsPopulate(Map<String, Object> map) { long t1 = System.currentTimeMillis(); for (int i = 0; i < LOOP_MAX_COUNT; i++) { try { TestClass bean = new TestClass(); BeanUtils.populate(bean, map); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } long t2 = System.currentTimeMillis(); System.out.println("BeanUtils t2-t1 = " + String.valueOf(t2 - t1)); } private static void runJacksonMapper(Map<String, Object> map) { long t1 = System.currentTimeMillis(); for (int i = 0; i < LOOP_MAX_COUNT; i++) { ObjectMapper mapper = new ObjectMapper(); TestClass testClass = mapper.convertValue(map, TestClass.class); } long t2 = System.currentTimeMillis(); System.out.println("Jackson t2-t1 = " + String.valueOf(t2 - t1)); } @Data @AllArgsConstructor @NoArgsConstructor public static class TestClass { private Boolean success; private Integer number; private Long longer; private Double doubler; private String data1; private String data2; private String data3; private String data4; private String data5; private String data6; private String data7; private String data8; private String data9; private String data10; } }

What is the Difference Between Mercurial and Git?

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

That is the essence of the difference.

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

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

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

MySQL - count total number of rows in php

use num_rows to get correct count for queries with conditions

$result = $connect->query("select * from table where id='$iid'");
$count=$result->num_rows;
echo "$count";

Adding ID's to google map markers

Why not use an cache that stores each marker object and references an ID?

var markerCache= {};
var idGen= 0;

function codeAddress(addr, contentStr){
    // create marker
    // store
    markerCache[idGen++]= marker;
}

Edit: of course this relies on a numeric index system that doesn't offer a length property like an array. You could of course prototype the Object object and create a length, etc for just such a thing. OTOH, generating a unique ID value (MD5, etc) of each address might be the way to go.

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

npm install errors with Error: ENOENT, chmod

You can get this error if your node.js is corrupted somehow as well. I fixed this error by uninstall/restart/install node.js completely and it fixed this error, along with the three other mysterious errors that are thrown.

Error: Uncaught SyntaxError: Unexpected token <

It usually works when you change the directory name, where the file is. It worked for me when I moved it from "js/" to "../js"

Groovy executing shell commands

To add one more important information to above provided answers -

For a process

def proc = command.execute();

always try to use

def outputStream = new StringBuffer();
proc.waitForProcessOutput(outputStream, System.err)
//proc.waitForProcessOutput(System.out, System.err)

rather than

def output = proc.in.text;

to capture the outputs after executing commands in groovy as the latter is a blocking call (SO question for reason).

node.js require() cache - possible to invalidate?

For anyone coming across this who is using Jest, because Jest does its own module caching, there's a built-in function for this - just make sure jest.resetModules runs eg. after each of your tests:

afterEach( function() {
  jest.resetModules();
});

Found this after trying to use decache like another answer suggested. Thanks to Anthony Garvan.

Function documentation here.

How to convert currentTimeMillis to a date in Java?

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timeStamp);

int mYear = calendar.get(Calendar.YEAR);
int mMonth = calendar.get(Calendar.MONTH);
int mDay = calendar.get(Calendar.DAY_OF_MONTH);

Facebook api: (#4) Application request limit reached

The Facebook "Graph API Rate Limiting" docs says that an error with code #4 is an app level rate limit, which is different than user level rate limits. Although it doesn't give any exact numbers, it describes their app level rate-limit as:

This rate limiting is applied globally at the app level. Ads api calls are excluded.

  • Rate limiting happens real time on sliding window for past one hour.
  • Stats is collected for number of calls and queries made, cpu time spent, memory used for each app.
  • There is a limit for each resource multiplied by monthly active users of a given app.
  • When the app uses more than its allowed resources the error is thrown.
  • Error, Code: 4, Message: Application request limit reached

The docs also give recommendations for avoiding the rate limits. For app level limits, they are:

Recommendations:

  • Verify the error code (4) to confirm the throttling type.
  • Do not make burst of calls, spread out the calls throughout the day.
  • Do smart fetching of data (important data, non duplicated data, etc).
    • Real-time insights, make sure API calls are structured in a way that you can read insights for as many as Page posts as possible, with minimum number of requests.
    • Don't fetch users feed twice (in the case that two App users have a specific friend in common)
    • Don't fetch all user's friends feed in a row if the number of friends is more than 250. Separate the fetches over different days. As an option, fetch first the app user's news feed (me/home) in order to detect which friends are more important to the App user. Then, fetch those friends feeds first.
  • Consider to limit/filter the requests by using the following parameters: "since", "until", "limit"
  • For page related calls use realtime updates to subscribe to changes in data.
  • Field expansion allows ton "join" multiple graph queries into a single call.
  • Etags to check if the data querying has changed since the last check.
  • For page management developers who does not have massive user base, have the admins of the page to accept the app to increase the number of users.

Finally, the docs give the following informational tips:

  • Batching calls will not reduce the number of api calls.
  • Making parallel calls will not reduce the number of api calls.

Using PI in python 2.7

To have access to stuff provided by math module, like pi. You need to import the module first:

import math
print (math.pi)

Delaying function in swift

You can use GCD (in the example with a 10 second delay):

Swift 2

let triggerTime = (Int64(NSEC_PER_SEC) * 10)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in
    self.functionToCall()
})

Swift 3 and Swift 4

DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
    self.functionToCall()
})

Swift 5 or Later

 DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
        //call any function
    }

convert big endian to little endian in C [without using provided func]

This code snippet can convert 32bit little Endian number to Big Endian number.

#include <stdio.h>
main(){    
    unsigned int i = 0xfafbfcfd;
    unsigned int j;    
    j= ((i&0xff000000)>>24)| ((i&0xff0000)>>8) | ((i&0xff00)<<8) | ((i&0xff)<<24);    
    printf("unsigned int j = %x\n ", j);    
}

proper way to sudo over ssh

Another way is to use the -t switch to ssh:

ssh -t user@server "sudo script"

See man ssh:

 -t      Force pseudo-tty allocation.  This can be used to execute arbi-
         trary screen-based programs on a remote machine, which can be
         very useful, e.g., when implementing menu services.  Multiple -t
         options force tty allocation, even if ssh has no local tty.

How to make a button redirect to another page using jQuery or just Javascript

You can use window.location

window.location="/newpage.php";

Or you can just make the form that the search button is in have a action of the page you want.

Java - How to find the redirected url of a url?

Have a look at the HttpURLConnection class API documentation, especially setInstanceFollowRedirects().

Detecting installed programs via registry

Seems like looking for something specific to the installed program would work better, but HKCU\Software and HKLM\Software are the spots to look.

How do I install chkconfig on Ubuntu?

Install this package in Ubuntu:

apt install sysv-rc-conf

its a substitute for chkconfig cmd.

After install run this cmd:

sysv-rc-conf --list

It'll show all services in all the runlevels. You can also run this:

sysv-rc-conf --level (runlevel number ex:1 2 3 4 5 6 )

Now you can choose which service should be active in boot time.

How to connect to mysql with laravel?

In Laravel 5, there is a .env file,

It looks like

APP_ENV=local
APP_DEBUG=true
APP_KEY=YOUR_API_KEY

DB_HOST=YOUR_HOST
DB_DATABASE=YOUR_DATABASE
DB_USERNAME=YOUR_USERNAME
DB_PASSWORD=YOUR_PASSWORD

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null

Edit that .env There is .env.sample is there , try to create from that if no such .env file found.

How to create localhost database using mysql?

removing temp files, and did you restart the computer or stop the MySQL service? That's the error message you get when there isn't a MySQL server running.

Get data from php array - AJAX - jQuery

you cannot access array (php array) from js try

<?php
$array = array(1,2,3,4,5,6);
echo implode('~',$array);
?>

and js

$(document).ready( function() {
$('#prev').click(function() {
  $.ajax({
  type: 'POST',
  url: 'ajax.php',
  data: 'id=testdata',
  cache: false,
  success: function(data) {
    result=data.split('~');
    $('#content1').html(result[0]);
  },
  });
});
});

How to remove the first character of string in PHP?

$str = substr($str, 1);

See PHP manual example 3

echo substr('abcdef', 1);     // bcdef

Note:

unset($str[0]) 

will not work as you cannot unset part of a string:-

Fatal error: Cannot unset string offsets

Remove a data connection from an Excel 2010 spreadsheet in compatibility mode

Excel 2010: On the File/Info page, go to 'Related Documents' and click break links => warning will appear that all linked values will be converted to their data values => click ok => done

How to get start and end of day in Javascript?

Using the momentjs library, this can be achieved with the startOf() and endOf() methods on the moment's current date object, passing the string 'day' as arguments:

Local GMT:

var start = moment().startOf('day'); // set to 12:00 am today
var end = moment().endOf('day'); // set to 23:59 pm today

For UTC:

var start = moment.utc().startOf('day'); 
var end = moment.utc().endOf('day'); 

Insert string at specified position

Try it, it will work for any number of substrings

<?php
    $string = 'bcadef abcdef';
    $substr = 'a';
    $attachment = '+++';

    //$position = strpos($string, 'a');

    $newstring = str_replace($substr, $substr.$attachment, $string);

    // bca+++def a+++bcdef
?>

What is ViewModel in MVC?

A lot of big examples, let me explain in clear and crispy way.

ViewModel = Model that is created to serve the view.

ASP.NET MVC view can't have more than one model so if we need to display properties from more than one models into the view, it is not possible. ViewModel serves this purpose.

View Model is a model class that can hold only those properties that is required for a view. It can also contains properties from more than one entities (tables) of the database. As the name suggests, this model is created specific to the View requirements.

Few examples of View Models are below

  • To list data from more than entities in a view page – we can create a View model and have properties of all the entities for which we want to list data. Join those database entities and set View model properties and return to the View to show data of different entities in one tabular form
  • View model may define only specific fields of a single entity that is required for the View.

ViewModel can also be used to insert, update records into more than one entities however the main use of ViewModel is to display columns from multiple entities (model) into a single view.

The way of creating ViewModel is same as creating Model, the way of creating view for the Viewmodel is same as creating view for Model.

Here is a small example of List data using ViewModel.

Hope this will be useful.

Possible to access MVC ViewBag object from Javascript file?

For CoreMVC 3.1, that would be,

@using Newtonsoft.Json
var listInJs =  @Html.Raw(JsonConvert.SerializeObject(ViewBag.SomeGenericList));

How to print a float with 2 decimal places in Java?

You may use this quick codes below that changed itself at the end. Add how many zeros as refers to after the point

float y1 = 0.123456789;
DecimalFormat df = new DecimalFormat("#.00");  
y1 = Float.valueOf(df.format(y1));

The variable y1 was equals to 0.123456789 before. After the code it turns into 0.12 only.

TypeError: 'list' object is not callable in python

If you are in a interactive session and don't want to restart you can remove the shadowing with

del list

Dealing with "java.lang.OutOfMemoryError: PermGen space" error

Perm gen space error occurs due to the use of large space rather then jvm provided space to executed the code.

The best solution for this problem in UNIX operating systems is to change some configuration on the bash file. The following steps solve the problem.

Run command gedit .bashrc on terminal.

Create JAVA_OTPS variable with following value:

export JAVA_OPTS="-XX:PermSize=256m -XX:MaxPermSize=512m"

Save the bash file. Run command exec bash on the terminal. Restart the server.

I hope this approach will work on your problem. If you use a Java version lower than 8 this issue occurs sometimes. But if you use Java 8 the problem never occurs.

How can I use a Python script in the command line without cd-ing to its directory? Is it the PYTHONPATH?

With PYTHONPATH set as in your example, you should be able to do

python -m gmbx

-m option will make Python search for your module in paths Python usually searches modules in, including what you added to PYTHONPATH. When you run interpreter like python gmbx.py, it looks for particular file and PYTHONPATH does not apply.

what is the most efficient way of counting occurrences in pandas?

When you want to count the frequency of categorical data in a column in pandas dataFrame use: df['Column_Name'].value_counts()

-Source.

How to make exe files from a node.js app?

I did find any of these solutions met my requirements, so made my own version of node called node2exe that does this. It's available from https://github.com/areve/node2exe

How do you roll back (reset) a Git repository to a particular commit?

When you say the 'GUI Tool', I assume you're using Git For Windows.

IMPORTANT, I would highly recommend creating a new branch to do this on if you haven't already. That way your master can remain the same while you test out your changes.

With the GUI you need to 'roll back this commit' like you have with the history on the right of your view. Then you will notice you have all the unwanted files as changes to commit on the left. Now you need to right click on the grey title above all the uncommited files and select 'disregard changes'. This will set your files back to how they were in this version.

How do I associate file types with an iPhone application?

In addition to Brad's excellent answer, I have found out that (on iOS 4.2.1 at least) when opening custom files from the Mail app, your app is not fired or notified if the attachment has been opened before. The "open with…" popup appears, but just does nothing.

This seems to be fixed by (re)moving the file from the Inbox directory. A safe approach seems to be to both (re)move the file as it is opened (in -(BOOL)application:openURL:sourceApplication:annotation:) as well as going through the Documents/Inbox directory, removing all items, e.g. in applicationDidBecomeActive:. That last catch-all may be needed to get the app in a clean state again, in case a previous import causes a crash or is interrupted.

Getting the Username from the HKEY_USERS values

It is possible to query this information from WMI. The following command will output a table with a row for every user along with the SID for each user.

wmic useraccount get name,sid

You can also export this information to CSV:

wmic useraccount get name,sid /format:csv > output.csv

I have used this on Vista and 7. For more information see WMIC - Take Command-line Control over WMI.

How to pass data from child component to its parent in ReactJS?

You can create the state in the ParentComponent using useState and pass down the setIsParentData function as prop into the ChildComponent.

In the ChildComponent, update the data using the received function through prop to send the data back to ParentComponent.

I use this technique especially when my code in the ParentComponent is getting too long, therefore I will create child components from the ParentComponent. Typically, it will be only 1 level down and using useContext or redux seems overkill in order to share states between components.

ParentComponent.js

import React, { useState } from 'react';
import ChildComponent from './ChildComponent';

export function ParentComponent(){
  const [isParentData, setIsParentData] = useState(True);

  return (
    <p>is this a parent data?: {isParentData}</p>
    <ChildComponent toChild={isParentData} sendToParent={setIsParentData} />
  );
}

ChildComponent.js

import React from 'react';

export function ChildComponent(props){

  return (
    <button onClick={() => {props.sendToParent(False)}}>Update</button>
    <p>The state of isParentData is {props.toChild}</p>
  );
};

Laravel 5.2 Missing required parameters for [Route: user.profile] [URI: user/{nickname}/profile]

Route::group(['middleware' => 'web'], function () {
Route::auth();

Route::get('/', ['as' => 'home', 'uses' => 'BaseController@index']);

Route::group(['namespace' => 'User', 'prefix' => 'user'], function(){
    Route::get('{nickname}/settings', ['as' => 'user.settings', 'uses' => 'SettingsController@index']);
    Route::get('{nickname}/profile', ['as' => 'user.profile', 'uses' => 'ProfileController@index']);
});
});

Maven build failed: "Unable to locate the Javac Compiler in: jre or jdk issue"

Use menu WindowPreferencesJavaInstalled JREsExecution Environments -> click the checkbox on the right side.

Ruby on Rails 3 Can't connect to local MySQL server through socket '/tmp/mysql.sock' on OSX

If you are running MYSQL through XAMPP:

  1. Open XAMPP mysql configuration file (on OSX):

    /Applications/XAMPP/etc/my.cnf

  2. Copy the socket path:

    socket = /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock

  3. Open rails project's database configuration file: myproject/config/database.yml

  4. Add the socket config to the development database config:

-->

development:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: difiuri_falcioni
  pool: 5
  username: root
  password:
  host: localhost
  socket: /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock
  1. Restart rails server

Enjoy :)

Get current time in milliseconds in Python?

If you're concerned about measuring elapsed time, you should use the monotonic clock (python 3). This clock is not affected by system clock updates like you would see if an NTP query adjusted your system time, for example.

>>> import time
>>> millis = round(time.monotonic() * 1000)

It provides a reference time in seconds that can be used to compare later to measure elapsed time.

C# convert int to string with padding zeros?

public static string ToLeadZeros(this int strNum, int num)
{
    var str = strNum.ToString();
    return str.PadLeft(str.Length + num, '0');
}

// var i = 1;
// string num = i.ToLeadZeros(5);

Must issue a STARTTLS command first

smtp port and socketFactory has to be change

    String to = "[email protected]";
    String subject = "subject"
    String msg ="email text...."
    final String from ="[email protected]"
    final  String password ="senderPassword"


    Properties props = new Properties();  
    props.setProperty("mail.transport.protocol", "smtp");     
    props.setProperty("mail.host", "smtp.gmail.com");  
    props.put("mail.smtp.auth", "true");  
    props.put("mail.smtp.port", "465");  
    props.put("mail.debug", "true");  
    props.put("mail.smtp.socketFactory.port", "465");  
    props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");  
    props.put("mail.smtp.socketFactory.fallback", "false");  
    Session session = Session.getDefaultInstance(props,  
    new javax.mail.Authenticator() {
       protected PasswordAuthentication getPasswordAuthentication() {  
       return new PasswordAuthentication(from,password);  
   }  
   });  

   //session.setDebug(true);  
   Transport transport = session.getTransport();  
   InternetAddress addressFrom = new InternetAddress(from);  

   MimeMessage message = new MimeMessage(session);  
   message.setSender(addressFrom);  
   message.setSubject(subject);  
   message.setContent(msg, "text/plain");  
   message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));  

   transport.connect();  
   Transport.send(message);  
   transport.close();
   }  

hope it will work for you..

Common HTTPclient and proxy

If your software uses a ProxySelector (for example for using a PAC-script instead of a static host/port) and your HTTPComponents is version 4.3 or above then you can use your ProxySelector for your HttpClient like this:

ProxySelector myProxySelector = ...;
HttpClient myHttpClient = HttpClientBuilder.create().setRoutePlanner(new SystemDefaultRoutePlanner(myProxySelector))).build();

And then do your requests as usual:

HttpGet myRequest = new HttpGet("/");
myHttpClient.execute(myRequest);

Could not read JSON: Can not deserialize instance of hello.Country[] out of START_OBJECT token

Another solution:

public class CountryInfoResponse {
  private List<Object> geonames;
}

Usage of a generic Object-List solved my problem, as there were other Datatypes like Boolean too.

How do I find duplicate values in a table in Oracle?

Another way:

SELECT *
FROM TABLE A
WHERE EXISTS (
  SELECT 1 FROM TABLE
  WHERE COLUMN_NAME = A.COLUMN_NAME
  AND ROWID < A.ROWID
)

Works fine (quick enough) when there is index on column_name. And it's better way to delete or update duplicate rows.

How to create many labels and textboxes dynamically depending on the value of an integer variable?

Suppose you have a button that when pressed sets n to 5, you could then generate labels and textboxes on your form like so.

var n = 5;
for (int i = 0; i < n; i++)
{
    //Create label
    Label label = new Label();
    label.Text = String.Format("Label {0}", i);
    //Position label on screen
    label.Left = 10;
    label.Top = (i + 1) * 20;
    //Create textbox
    TextBox textBox = new TextBox();
    //Position textbox on screen
    textBox.Left = 120;
    textBox.Top = (i + 1) * 20;
    //Add controls to form
    this.Controls.Add(label);
    this.Controls.Add(textBox);
}

This will not only add them to the form but position them decently as well.

How to change port number for apache in WAMP

In addition of the modification of the file C:\wamp64\bin\apache\apache2.4.27\conf\httpd.conf.
To get the url shortcuts working, edit the file C:\wamp64\wampmanager.conf and change the port:

[apache]
apachePortUsed = "8080"

Then exit and relaunch wamp.

how to console.log result of this ajax call?

$.ajax({
    type: 'POST',
    url: 'loginCheck',
    data: $(formLogin).serialize(),    
    success: function(result){
        console.log('my message' + result);
    }
});

Get current time as formatted string in Go?

All the other response are very miss-leading for somebody coming from google and looking for "timestamp in go"! YYYYMMDDhhmmss is not a "timestamp".

To get the "timestamp" of a date in go (number of seconds from january 1970), the correct function is .Unix(), and it really return an integer

C++ vector of char array

Use std::string instead of char-arrays

std::string k ="abcde";
std::vector<std::string> v;
v.push_back(k);

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

How To have Dynamic SQL in MySQL Stored Procedure

I don't believe MySQL supports dynamic sql. You can do "prepared" statements which is similar, but different.

Here is an example:

mysql> PREPARE stmt FROM 
    -> 'select count(*) 
    -> from information_schema.schemata 
    -> where schema_name = ? or schema_name = ?'
;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE stmt 
    -> USING @schema1,@schema2
+----------+
| count(*) |
+----------+
|        2 |
+----------+
1 row in set (0.00 sec)
mysql> DEALLOCATE PREPARE stmt;

The prepared statements are often used to see an execution plan for a given query. Since they are executed with the execute command and the sql can be assigned to a variable you can approximate the some of the same behavior as dynamic sql.

Here is a good link about this:

Don't forget to deallocate the stmt using the last line!

Good Luck!

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

Since there is so much confusion about functionality of standard service accounts, I'll try to give a quick run down.

First the actual accounts:

  • LocalService account (preferred)

    A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user.

    • Name: NT AUTHORITY\LocalService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the LocalService user account
    • has minimal privileges on the local computer
    • presents anonymous credentials on the network
    • SID: S-1-5-19
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-19)

     

  • NetworkService account

    Limited service account that is meant to run standard privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine (see caveat above).

    • NT AUTHORITY\NetworkService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the NetworkService user account
    • has minimal privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers
    • SID: S-1-5-20
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-20)
    • If trying to schedule a task using it, enter NETWORK SERVICE into the Select User or Group dialog

     

  • LocalSystem account (dangerous, don't use!)

    Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)

    • Name: .\LocalSystem (can also use LocalSystem or ComputerName\LocalSystem)
    • the account has no password (any password information you provide is ignored)
    • SID: S-1-5-18
    • does not have any profile of its own (HKCU represents the default user)
    • has extensive privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers

     

Above when talking about accessing the network, this refers solely to SPNEGO (Negotiate), NTLM and Kerberos and not to any other authentication mechanism. For example, processing running as LocalService can still access the internet.

The general issue with running as a standard out of the box account is that if you modify any of the default permissions you're expanding the set of things everything running as that account can do. So if you grant DBO to a database, not only can your service running as Local Service or Network Service access that database but everything else running as those accounts can too. If every developer does this the computer will have a service account that has permissions to do practically anything (more specifically the superset of all of the different additional privileges granted to that account).

It is always preferable from a security perspective to run as your own service account that has precisely the permissions you need to do what your service does and nothing else. However, the cost of this approach is setting up your service account, and managing the password. It's a balancing act that each application needs to manage.

In your specific case, the issue that you are probably seeing is that the the DCOM or COM+ activation is limited to a given set of accounts. In Windows XP SP2, Windows Server 2003, and above the Activation permission was restricted significantly. You should use the Component Services MMC snapin to examine your specific COM object and see the activation permissions. If you're not accessing anything on the network as the machine account you should seriously consider using Local Service (not Local System which is basically the operating system).


In Windows Server 2003 you cannot run a scheduled task as

  • NT_AUTHORITY\LocalService (aka the Local Service account), or
  • NT AUTHORITY\NetworkService (aka the Network Service account).

That capability only was added with Task Scheduler 2.0, which only exists in Windows Vista/Windows Server 2008 and newer.

A service running as NetworkService presents the machine credentials on the network. This means that if your computer was called mango, it would present as the machine account MANGO$:

enter image description here

How can I format DateTime to web UTC format?

This code is working for me:

var datetime = new DateTime(2017, 10, 27, 14, 45, 53, 175, DateTimeKind.Local);
var text = datetime.ToString("o");
Console.WriteLine(text);
--  2017-10-27T14:45:53.1750000+03:00

// datetime from string
var newDate = DateTime.ParseExact(text, "o", null);

How Does Modulus Divison Work

Lets say you have 17 mod 6.

what total of 6 will get you the closest to 17, it will be 12 because if you go over 12 you will have 18 which is more that the question of 17 mod 6. You will then take 12 and minus from 17 which will give you your answer, in this case 5.

17 mod 6=5

Stripping everything but alphanumeric chars from a string in Python

sent = "".join(e for e in sent if e.isalpha())

How can I remove a commit on GitHub?

It is not very good to re-write the history. If we use git revert <commit_id>, it creates a clean reverse-commit of the said commit id.

This way, the history is not re-written, instead, everyone knows that there has been a revert.

In Bootstrap open Enlarge image in modal

You can try this code if you are using bootstrap 3:

HTML

<a href="#" id="pop">
    <img id="imageresource" src="http://patyshibuya.com.br/wp-content/uploads/2014/04/04.jpg" style="width: 400px; height: 264px;">
    Click to Enlarge
</a>

<!-- Creates the bootstrap modal where the image will appear -->
<div class="modal fade" id="imagemodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
        <h4 class="modal-title" id="myModalLabel">Image preview</h4>
      </div>
      <div class="modal-body">
        <img src="" id="imagepreview" style="width: 400px; height: 264px;" >
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

JavaScript:

$("#pop").on("click", function() {
   $('#imagepreview').attr('src', $('#imageresource').attr('src')); // here asign the image to the modal when the user click the enlarge link
   $('#imagemodal').modal('show'); // imagemodal is the id attribute assigned to the bootstrap modal, then i use the show function
});

This is the working fiddle. Hope this helps :)

Use PHP composer to clone git repo

At the time of writing in 2013, this was one way to do it. Composer has added support for better ways: See @igorw 's answer

DO YOU HAVE A REPOSITORY?

Git, Mercurial and SVN is supported by Composer.

DO YOU HAVE WRITE ACCESS TO THE REPOSITORY?

Yes?

DOES THE REPOSITORY HAVE A composer.json FILE

If you have a repository you can write to: Add a composer.json file, or fix the existing one, and DON'T use the solution below.

Go to @igorw 's answer

ONLY USE THIS IF YOU DON'T HAVE A REPOSITORY
OR IF THE REPOSITORY DOES NOT HAVE A composer.json AND YOU CANNOT ADD IT

This will override everything that Composer may be able to read from the original repository's composer.json, including the dependencies of the package and the autoloading.

Using the package type will transfer the burden of correctly defining everything onto you. The easier way is to have a composer.json file in the repository, and just use it.

This solution really only is for the rare cases where you have an abandoned ZIP download that you cannot alter, or a repository you can only read, but it isn't maintained anymore.

"repositories": [
    {
        "type":"package",
        "package": {
          "name": "l3pp4rd/doctrine-extensions",
          "version":"master",
          "source": {
              "url": "https://github.com/l3pp4rd/DoctrineExtensions.git",
              "type": "git",
              "reference":"master"
            }
        }
    }
],
"require": {
    "l3pp4rd/doctrine-extensions": "master"
}

What is the difference between primary, unique and foreign key constraints, and indexes?

1)A primary key is a set of one or more attributes that uniquely identifies tuple within relation.

2)A foreign key is a set of attributes from a relation scheme which can be uniquely identify tuples fron another relation scheme.

How to export plots from matplotlib with transparent background?

Png files can handle transparency. So you could use this question Save plot to image file instead of displaying it using Matplotlib so as to save you graph as a png file.

And if you want to turn all white pixel transparent, there's this other question : Using PIL to make all white pixels transparent?

If you want to turn an entire area to transparent, then there's this question: And then use the PIL library like in this question Python PIL: how to make area transparent in PNG? so as to make your graph transparent.

How is "mvn clean install" different from "mvn install"?

clean is its own build lifecycle phase (which can be thought of as an action or task) in Maven. mvn clean install tells Maven to do the clean phase in each module before running the install phase for each module.

What this does is clear any compiled files you have, making sure that you're really compiling each module from scratch.

msvcr110.dll is missing from computer error while installing PHP

I had installed PHP in IIS7 on Windows Server 2008 R2 using the Web Platform Installer. It did not work out of the box. I had to install the Visual C++ Redistributable for VS 2012 Update 4 (32bit) as found here http://www.microsoft.com/en-us/download/details.aspx?id=30679 .

Cannot push to Git repository on Bitbucket

I found the git command line didnt fancy my pageant generated keys (Windows 10).

See my answer on Serverfault

SQL Server command line backup statement

if you need the batch file to schedule the backup, the SQL management tools have scheduled tasks built in...

Do I cast the result of malloc?

In C you get an implicit conversion from void * to any other (data) pointer.

Do I commit the package-lock.json file created by npm 5?

Yes, you SHOULD:

  1. commit the package-lock.json.
  2. use npm ci instead of npm install when building your applications both on your CI and your local development machine

The npm ci workflow requires the existence of a package-lock.json.


A big downside of npm install command is its unexpected behavior that it may mutate the package-lock.json, whereas npm ci only uses the versions specified in the lockfile and produces an error

  • if the package-lock.json and package.json are out of sync
  • if a package-lock.json is missing.

Hence, running npm install locally, esp. in larger teams with multiple developers, may lead to lots of conflicts within the package-lock.json and developers to decide to completely delete the package-lock.json instead.

Yet there is a strong use-case for being able to trust that the project's dependencies resolve repeatably in a reliable way across different machines.

From a package-lock.json you get exactly that: a known-to-work state.

In the past, I had projects without package-lock.json / npm-shrinkwrap.json / yarn.lock files whose build would fail one day because a random dependency got a breaking update.

Those issue are hard to resolve as you sometimes have to guess what the last working version was.

If you want to add a new dependency, you still run npm install {dependency}. If you want to upgrade, use either npm update {dependency} or npm install ${dependendency}@{version} and commit the changed package-lock.json.

If an upgrade fails, you can revert to the last known working package-lock.json.


To quote npm doc:

It is highly recommended you commit the generated package lock to source control: this will allow anyone else on your team, your deployments, your CI/continuous integration, and anyone else who runs npm install in your package source to get the exact same dependency tree that you were developing on. Additionally, the diffs from these changes are human-readable and will inform you of any changes npm has made to your node_modules, so you can notice if any transitive dependencies were updated, hoisted, etc.

And in regards to the difference between npm ci vs npm install:

  • The project must have an existing package-lock.json or npm-shrinkwrap.json.
  • If dependencies in the package lock do not match those in package.json, npm ci will exit with an error, instead of updating the package lock.
  • npm ci can only install entire projects at a time: individual dependencies cannot be added with this command.
  • If a node_modules is already present, it will be automatically removed before npm ci begins its install.
  • It will never write to package.json or any of the package-locks: installs are essentially frozen.

Note: I posted a similar answer here

PHP, How to get current date in certain format

date("Y-m-d H:i:s"); // This should do it.

How to redirect the output of print to a TXT file

simple in python 3.6

o = open('outfile','w')

print('hello world', file=o)

o.close()

I was looking for something like I did in Perl

my $printname = "outfile"

open($ph, '>', $printname)
    or die "Could not open file '$printname' $!";

print $ph "hello world\n";

Updating version numbers of modules in a multi-module Maven project

You may want to look into Maven release plugin's release:update-versions goal. It will update the parent's version as well as all the modules under it.


Update: Please note that the above is the release plugin. If you are not releasing, you may want to use versions:set

mvn versions:set -DnewVersion=1.2.3-SNAPSHOT

How to provide shadow to Button

Android now provides ExtendedFloatingActionButton which does the same thing for you.

Clear data in MySQL table with PHP?

TRUNCATE TABLE tablename

or

DELETE FROM tablename

The first one is usually the better choice, as DELETE FROM is slow on InnoDB.

Actually, wasn't this already answered in your other question?

Eclipse CDT: Symbol 'cout' could not be resolved

Most likely you have some system-specific include directories missing in your settings which makes it impossible for indexer to correctly parse iostream, thus the errors. Selecting Index -> Search For Unresolved Includes in the context menu of the project will give you the list of unresolved includes which you can search in /usr/include and add containing directories to C++ Include Paths and Symbols in Project Properties.

On my system I had to add /usr/include/c++/4.6/x86_64-linux-gnu for bits/c++config.h to be resolved and a few more directories.

Don't forget to rebuild the index (Index -> Rebuild) after adding include directories.

MySQL table is marked as crashed and last (automatic?) repair failed

If this happend to your XAMPP installation, just copy global_priv.MAD and global_priv.MAI files from ./xampp/mysql/backup/mysql/ to ./xampp/mysql/data/mysql/.

How to reference static assets within vue javascript

Right after oppening script tag just add import someImage from '../assets/someImage.png' and use it for an icon url iconUrl: someImage

Hidden Features of C#?

Math.Max and Min to check boundaries: I 've seen this in a lot of code:

if (x < lowerBoundary) 
{
   x = lowerBoundary;
}

I find this smaller, cleaner and more readable:

x = Math.Max(x, lowerBoundary);

Or you can also use a ternary operator:

x = ( x < lowerBoundary) ? lowerBoundary : x;

Removing elements from an array in C

You don't really want to be reallocing memory every time you remove something. If you know the rough size of your deck then choose an appropriate size for your array and keep a pointer to the current end of the list. This is a stack.

If you don't know the size of your deck, and think it could get really big as well as keeps changing size, then you will have to do something a little more complex and implement a linked-list.

In C, you have two simple ways to declare an array.

  1. On the stack, as a static array

    int myArray[16]; // Static array of 16 integers
    
  2. On the heap, as a dynamically allocated array

    // Dynamically allocated array of 16 integers
    int* myArray = calloc(16, sizeof(int));
    

Standard C does not allow arrays of either of these types to be resized. You can either create a new array of a specific size, then copy the contents of the old array to the new one, or you can follow one of the suggestions above for a different abstract data type (ie: linked list, stack, queue, etc).

How to Implement DOM Data Binding in JavaScript

It is very simple two way data binding in vanilla javascript....

<input type="text" id="inp" onkeyup="document.getElementById('name').innerHTML=document.getElementById('inp').value;">

<div id="name">

</div>

How to change font-size of a tag using inline css?

use this attribute in style

font-size: 11px !important;//your font size

by !important it override your css

QR Code encoding and decoding using zxing

If you really need to encode UTF-8, you can try prepending the unicode byte order mark. I have no idea how widespread the support for this method is, but ZXing at least appears to support it: http://code.google.com/p/zxing/issues/detail?id=103

I've been reading up on QR Mode recently, and I think I've seen the same practice mentioned elsewhere, but I've not the foggiest where.

Smooth scroll without the use of jQuery

I recently set out to solve this problem in a situation where jQuery wasn't an option, so I'm logging my solution here just for posterity.

var scroll = (function() {

    var elementPosition = function(a) {
        return function() {
            return a.getBoundingClientRect().top;
        };
    };

    var scrolling = function( elementID ) {

        var el = document.getElementById( elementID ),
            elPos = elementPosition( el ),
            duration = 400,
            increment = Math.round( Math.abs( elPos() )/40 ),
            time = Math.round( duration/increment ),
            prev = 0,
            E;

        function scroller() {
            E = elPos();

            if (E === prev) {
                return;
            } else {
                prev = E;
            }

            increment = (E > -20 && E < 20) ? ((E > - 5 && E < 5) ? 1 : 5) : increment;

            if (E > 1 || E < -1) {

                if (E < 0) {
                    window.scrollBy( 0,-increment );
                } else {
                    window.scrollBy( 0,increment );
                }

                setTimeout(scroller, time);

            } else {

                el.scrollTo( 0,0 );

            }
        }

        scroller();
    };

    return {
        To: scrolling
    }

})();

/* usage */
scroll.To('elementID');

The scroll() function uses the Revealing Module Pattern to pass the target element's id to its scrolling() function, via scroll.To('id'), which sets the values used by the scroller() function.

Breakdown

In scrolling():

  • el : the target DOM object
  • elPos : returns a function via elememtPosition() which gives the position of the target element relative to the top of the page each time it's called.
  • duration : transition time in milliseconds.
  • increment : divides the starting position of the target element into 40 steps.
  • time : sets the timing of each step.
  • prev : the target element's previous position in scroller().
  • E : holds the target element's position in scroller().

The actual work is done by the scroller() function which continues to call itself (via setTimeout()) until the target element is at the top of the page or the page can scroll no more.

Each time scroller() is called it checks the current position of the target element (held in variable E) and if that is > 1 OR < -1 and if the page is still scrollable shifts the window by increment pixels - up or down depending if E is a positive or negative value. When E is neither > 1 OR < -1, or E === prev the function stops. I added the DOMElement.scrollTo() method on completion just to make sure the target element was bang on the top of the window (not that you'd notice it being out by a fraction of a pixel!).

The if statement on line 2 of scroller() checks to see if the page is scrolling (in cases where the target might be towards the bottom of the page and the page can scroll no further) by checking E against its previous position (prev).

The ternary condition below it reduce the increment value as E approaches zero. This stops the page overshooting one way and then bouncing back to overshoot the other, and then bouncing back to overshoot the other again, ping-pong style, to infinity and beyond.

If your page is more that c.4000px high you might want to increase the values in the ternary expression's first condition (here at +/-20) and/or the divisor which sets the increment value (here at 40).

Playing about with duration, the divisor which sets increment, and the values in the ternary condition of scroller() should allow you to tailor the function to suit your page.

  • JSFiddle

  • N.B.Tested in up-to-date versions of Firefox and Chrome on Lubuntu, and Firefox, Chrome and IE on Windows8.

SimpleDateFormat and locale based format string

SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE dd MMM yyyy", Locale.ENGLISH);
String formatted = dateFormat.format(the_date_you_want_here);

How do you remove all the options of a select box and then add one option and select it with jQuery?

why not just use plain javascript?

document.getElementById("selectID").options.length = 0;

React: Expected an assignment or function call and instead saw an expression

The return statements should place in one line. Or the other option is to remove the curly brackets that bound the HTML statement.

example:

return posts.map((post, index) =>
    <div key={index}>
      <h3>{post.title}</h3>
      <p>{post.body}</p>
    </div>
);

angular 2 how to return data from subscribe

You just can't return the value directly because it is an async call. An async call means it is running in the background (actually scheduled for later execution) while your code continues to execute.

You also can't have such code in the class directly. It needs to be moved into a method or the constructor.

What you can do is not to subscribe() directly but use an operator like map()

export class DataComponent{
    someMethod() {
      return this.http.get(path).map(res => {
        return res.json();
      });
    }
}

In addition, you can combine multiple .map with the same Observables as sometimes this improves code clarity and keeps things separate. Example:

validateResponse = (response) => validate(response);

parseJson = (json) => JSON.parse(json);

fetchUnits() {
    return this.http.get(requestUrl).map(this.validateResponse).map(this.parseJson);
}

This way an observable will be return the caller can subscribe to

export class DataComponent{
    someMethod() {
      return this.http.get(path).map(res => {
        return res.json();
      });
    }

    otherMethod() {
      this.someMethod().subscribe(data => this.data = data);
    }
}

The caller can also be in another class. Here it's just for brevity.

data => this.data = data

and

res => return res.json()

are arrow functions. They are similar to normal functions. These functions are passed to subscribe(...) or map(...) to be called from the observable when data arrives from the response. This is why data can't be returned directly, because when someMethod() is completed, the data wasn't received yet.

How to compile and run a C/C++ program on the Android system

You can compile your C programs with an ARM cross-compiler:

arm-linux-gnueabi-gcc -static -march=armv7-a test.c -o test

Then you can push your compiled binary file to somewhere (don't push it in to the SD card):

adb push test /data/local/tmp/test

Can I force a page break in HTML printing?

I was struggling this for some time, it never worked.

In the end, the solution was to put a style element in the head.

The page-break-after can't be in a linked CSS file, it must be in the HTML itself.

Are HTTP cookies port specific?

According to RFC2965 3.3.1 (which might or might not be followed by browsers), unless the port is explicitly specified via the port parameter of the Set-Cookie header, cookies might or might not be sent to any port.

Google's Browser Security Handbook says: by default, cookie scope is limited to all URLs on the current host name - and not bound to port or protocol information. and some lines later There is no way to limit cookies to a single DNS name only [...] likewise, there is no way to limit them to a specific port. (Also, keep in mind, that IE does not factor port numbers into its same-origin policy at all.)

So it does not seem to be safe to rely on any well-defined behavior here.

Carousel with Thumbnails in Bootstrap 3.0

Just found out a great plugin for this:

http://flexslider.woothemes.com/

Regards

How do I install a custom font on an HTML site

there is a simple way to do this: in the html file add:

<link rel="stylesheet" href="fonts/vermin_vibes.ttf" />

Note: you put the name of .ttf file you have. then go to to your css file and add:

h1 {
    color: blue;
    font-family: vermin vibes;
}

Note: you put the font family name of the font you have.

Note: do not write the font-family name as your font.ttf name example: if your font.ttf name is: "vermin_vibes.ttf" your font-family will be: "vermin vibes" font family doesn't contain special chars as "-,_"...etc it only can contain spaces.

How to get file size in Java

Try this:

long length = f.length();

Setting up enviromental variables in Windows 10 to use java and javac

Here are the typical steps to set JAVA_HOME on Windows 10.

  1. Search for Advanced System Settings in your windows Search box. Click on Advanced System Settings.
  2. Click on Environment variables button: Environment Variables popup will open.
  3. Goto system variables session, and click on New button to create new variable (HOME_PATH), then New System Variables popup will open.
  4. Give Variable Name: JAVA_HOME, and Variable value : Your Java SDK home path. Ex: C:\Program Files\java\jdk1.8.0_151 Note: It should not include \bin. Then click on OK button.
  5. Now you are able to see your JAVA_HOME in system variables list. (If you are not able to, try doing it again.)
  6. Select Path (from system variables list) and click on Edit button, A new pop will opens (Edit Environment Variables). It was introduced in windows 10.
  7. Click on New button and give %JAVA_HOME%\bin at highlighted field and click Ok button.

You can find complete tutorials on my blog :

How to set JAVA_HOME in 64 bit Windows 10 OS

How to set level logging to DEBUG in Tomcat?

JULI logging levels for Tomcat

SEVERE - Serious failures

WARNING - Potential problems

INFO - Informational messages

CONFIG - Static configuration messages

FINE - Trace messages

FINER - Detailed trace messages

FINEST - Highly detailed trace messages

You can find here more https://documentation.progress.com/output/ua/OpenEdge_latest/index.html#page/pasoe-admin/tomcat-logging.html

Error with multiple definitions of function

Here is a highly simplified but hopefully relevant view of what happens when you build your code in C++.

C++ splits the load of generating machine executable code in following different phases -

  1. Preprocessing - This is where any macros - #defines etc you might be using get expanded.

  2. Compiling - Each cpp file along with all the #included files in that file directly or indirectly (together called a compilation unit) is converted into machine readable object code.

    This is where C++ also checks that all functions defined (i.e. containing a body in { } e.g. void Foo( int x){ return Boo(x); }) are referring to other functions in a valid manner.

    The way it does that is by insisting that you provide at least a declaration of these other functions (e.g. void Boo(int); ) before you call it so it can check that you are calling it properly among other things. This can be done either directly in the cpp file where it is called or usually in an included header file.

    Note that only the machine code that corresponds to functions defined in this cpp and included files gets built as the object (binary) version of this compilation unit (e.g. Foo) and not the ones that are merely declared (e.g. Boo).

  3. Linking - This is the stage where C++ goes hunting for stuff declared and called in each compilation unit and links it to the places where it is getting called. Now if there was no definition found of this function the linker gives up and errors out. Similarly if it finds multiple definitions of the same function signature (essentially the name and parameter types it takes) it also errors out as it considers it ambiguous and doesn't want to pick one arbitrarily.

The latter is what is happening in your case. By doing a #include of the fun.cpp file, both fun.cpp and mainfile.cpp have a definition of funct() and the linker doesn't know which one to use in your program and is complaining about it.

The fix as Vaughn mentioned above is to not include the cpp file with the definition of funct() in mainfile.cpp and instead move the declaration of funct() in a separate header file and include that in mainline.cpp. This way the compiler will get the declaration of funct() to work with and the linker would get just one definition of funct() from fun.cpp and will use it with confidence.

Java reverse an int value without using array

It's good that you wrote out your original code. I have another way to code this concept of reversing an integer. I'm only going to allow up to 10 digits. However, I am going to make the assumption that the user will not enter a zero.

if((inputNum <= 999999999)&&(inputNum > 0 ))
{
   System.out.print("Your number reversed is: ");

   do
   {
      endInt = inputNum % 10; //to get the last digit of the number
      inputNum /= 10;
      system.out.print(endInt);
   }
   While(inputNum != 0);
 System.out.println("");

}
 else
   System.out.println("You used an incorrect number of integers.\n");

System.out.println("Program end");

Difference between numpy dot() and Python 3.5+ matrix multiplication @

The @ operator calls the array's __matmul__ method, not dot. This method is also present in the API as the function np.matmul.

>>> a = np.random.rand(8,13,13)
>>> b = np.random.rand(8,13,13)
>>> np.matmul(a, b).shape
(8, 13, 13)

From the documentation:

matmul differs from dot in two important ways.

  • Multiplication by scalars is not allowed.
  • Stacks of matrices are broadcast together as if the matrices were elements.

The last point makes it clear that dot and matmul methods behave differently when passed 3D (or higher dimensional) arrays. Quoting from the documentation some more:

For matmul:

If either argument is N-D, N > 2, it is treated as a stack of matrices residing in the last two indexes and broadcast accordingly.

For np.dot:

For 2-D arrays it is equivalent to matrix multiplication, and for 1-D arrays to inner product of vectors (without complex conjugation). For N dimensions it is a sum product over the last axis of a and the second-to-last of b

Dead simple example of using Multiprocessing Queue, Pool and Locking

Here is an example from my code (for threaded pool, but just change class name and you'll have process pool):

def execute_run(rp): 
   ... do something 

pool = ThreadPoolExecutor(6)
for mat in TESTED_MATERIAL:
    for en in TESTED_ENERGIES:
        for ecut in TESTED_E_CUT:
            rp = RunParams(
                simulations, DEST_DIR,
                PARTICLE, mat, 960, 0.125, ecut, en
            )
            pool.submit(execute_run, rp)
pool.join()

Basically:

  • pool = ThreadPoolExecutor(6) creates a pool for 6 threads
  • Then you have bunch of for's that add tasks to the pool
  • pool.submit(execute_run, rp) adds a task to pool, first arogument is a function called in in a thread/process, rest of the arguments are passed to the called function.
  • pool.join waits until all tasks are done.

Generate a heatmap in MatPlotLib using a scatter data set

and the initial question was... how to convert scatter values to grid values, right? histogram2d does count the frequency per cell, however, if you have other data per cell than just the frequency, you'd need some additional work to do.

x = data_x # between -10 and 4, log-gamma of an svc
y = data_y # between -4 and 11, log-C of an svc
z = data_z #between 0 and 0.78, f1-values from a difficult dataset

So, I have a dataset with Z-results for X and Y coordinates. However, I was calculating few points outside the area of interest (large gaps), and heaps of points in a small area of interest.

Yes here it becomes more difficult but also more fun. Some libraries (sorry):

from matplotlib import pyplot as plt
from matplotlib import cm
import numpy as np
from scipy.interpolate import griddata

pyplot is my graphic engine today, cm is a range of color maps with some initeresting choice. numpy for the calculations, and griddata for attaching values to a fixed grid.

The last one is important especially because the frequency of xy points is not equally distributed in my data. First, let's start with some boundaries fitting to my data and an arbitrary grid size. The original data has datapoints also outside those x and y boundaries.

#determine grid boundaries
gridsize = 500
x_min = -8
x_max = 2.5
y_min = -2
y_max = 7

So we have defined a grid with 500 pixels between the min and max values of x and y.

In my data, there are lots more than the 500 values available in the area of high interest; whereas in the low-interest-area, there are not even 200 values in the total grid; between the graphic boundaries of x_min and x_max there are even less.

So for getting a nice picture, the task is to get an average for the high interest values and to fill the gaps elsewhere.

I define my grid now. For each xx-yy pair, i want to have a color.

xx = np.linspace(x_min, x_max, gridsize) # array of x values
yy = np.linspace(y_min, y_max, gridsize) # array of y values
grid = np.array(np.meshgrid(xx, yy.T))
grid = grid.reshape(2, grid.shape[1]*grid.shape[2]).T

Why the strange shape? scipy.griddata wants a shape of (n, D).

Griddata calculates one value per point in the grid, by a predefined method. I choose "nearest" - empty grid points will be filled with values from the nearest neighbor. This looks as if the areas with less information have bigger cells (even if it is not the case). One could choose to interpolate "linear", then areas with less information look less sharp. Matter of taste, really.

points = np.array([x, y]).T # because griddata wants it that way
z_grid2 = griddata(points, z, grid, method='nearest')
# you get a 1D vector as result. Reshape to picture format!
z_grid2 = z_grid2.reshape(xx.shape[0], yy.shape[0])

And hop, we hand over to matplotlib to display the plot

fig = plt.figure(1, figsize=(10, 10))
ax1 = fig.add_subplot(111)
ax1.imshow(z_grid2, extent=[x_min, x_max,y_min, y_max,  ],
            origin='lower', cmap=cm.magma)
ax1.set_title("SVC: empty spots filled by nearest neighbours")
ax1.set_xlabel('log gamma')
ax1.set_ylabel('log C')
plt.show()

Around the pointy part of the V-Shape, you see I did a lot of calculations during my search for the sweet spot, whereas the less interesting parts almost everywhere else have a lower resolution.

Heatmap of a SVC in high resolution

Select the first row by group

You can use duplicated to do this very quickly.

test[!duplicated(test$id),]

Benchmarks, for the speed freaks:

ju <- function() test[!duplicated(test$id),]
gs1 <- function() do.call(rbind, lapply(split(test, test$id), head, 1))
gs2 <- function() do.call(rbind, lapply(split(test, test$id), `[`, 1, ))
jply <- function() ddply(test,.(id),function(x) head(x,1))
jdt <- function() {
  testd <- as.data.table(test)
  setkey(testd,id)
  # Initial solution (slow)
  # testd[,lapply(.SD,function(x) head(x,1)),by = key(testd)]
  # Faster options :
  testd[!duplicated(id)]               # (1)
  # testd[, .SD[1L], by=key(testd)]    # (2)
  # testd[J(unique(id)),mult="first"]  # (3)
  # testd[ testd[,.I[1L],by=id] ]      # (4) needs v1.8.3. Allows 2nd, 3rd etc
}

library(plyr)
library(data.table)
library(rbenchmark)

# sample data
set.seed(21)
test <- data.frame(id=sample(1e3, 1e5, TRUE), string=sample(LETTERS, 1e5, TRUE))
test <- test[order(test$id), ]

benchmark(ju(), gs1(), gs2(), jply(), jdt(),
    replications=5, order="relative")[,1:6]
#     test replications elapsed relative user.self sys.self
# 1   ju()            5    0.03    1.000      0.03     0.00
# 5  jdt()            5    0.03    1.000      0.03     0.00
# 3  gs2()            5    3.49  116.333      2.87     0.58
# 2  gs1()            5    3.58  119.333      3.00     0.58
# 4 jply()            5    3.69  123.000      3.11     0.51

Let's try that again, but with just the contenders from the first heat and with more data and more replications.

set.seed(21)
test <- data.frame(id=sample(1e4, 1e6, TRUE), string=sample(LETTERS, 1e6, TRUE))
test <- test[order(test$id), ]
benchmark(ju(), jdt(), order="relative")[,1:6]
#    test replications elapsed relative user.self sys.self
# 1  ju()          100    5.48    1.000      4.44     1.00
# 2 jdt()          100    6.92    1.263      5.70     1.15

Can I load a .NET assembly at runtime and instantiate a type knowing only the name?

Consider the limitations of the different Load* methods. From the MSDN docs...

LoadFile does not load files into the LoadFrom context, and does not resolve dependencies using the load path, as the LoadFrom method does.

More information on Load Contexts can be found in the LoadFrom docs.

What does %>% function mean in R?

My understanding after reading the link offered by G.Grothendieck is that %>% is an operator that pipes functions. This helps readability and productivity as it's easier to follow the flow of multiple functions through these pipes than going backwards when multiple function are nested.

Linking static libraries to other static libraries

On Linux or MingW, with GNU toolchain:

ar -M <<EOM
    CREATE libab.a
    ADDLIB liba.a
    ADDLIB libb.a
    SAVE
    END
EOM
ranlib libab.a

Of if you do not delete liba.a and libb.a, you can make a "thin archive":

ar crsT libab.a liba.a libb.a

On Windows, with MSVC toolchain:

lib.exe /OUT:libab.lib liba.lib libb.lib

Convert Time DataType into AM PM Format:

Try this:

select CONVERT(VARCHAR(5), ' 4:07PM', 108) + ' ' + RIGHT(CONVERT(VARCHAR(30), ' 4:07PM', 9),2) as ConvertedTime

Logout button php

When you want to destroy a session completely, you need to do more then just

session_destroy();

First, you should unset any session variables. Then you should destroy the session followed by closing the write of the session. This can be done by the following:

<?php
session_start();
unset($_SESSION);
session_destroy();
session_write_close();
header('Location: /');
die;
?>

The reason you want have a separate script for a logout is so that you do not accidently execute it on the page. So make a link to your logout script, then the header will redirect to the root of your site.

Edit:

You need to remove the () from your exit code near the top of your script. it should just be

exit;

Check if key exists in JSON object using jQuery

if(typeof theObject['key'] != 'undefined'){
     //key exists, do stuff
}

//or

if(typeof theObject.key != 'undefined'){
    //object exists, do stuff
}

I'm writing here because no one seems to give the right answer..

I know it's old...

Somebody might question the same thing..

Is there a program to decompile Delphi?

Here's a list : http://delphi.about.com/od/devutilities/a/decompiling_3.htm (and this page mentions some more : http://www.program-transformation.org/Transform/DelphiDecompilers )

I've used DeDe on occasion, but it's not really all that powerfull, and it's not up-to-date with current Delphi versions (latest version it supports is Delphi 7 I believe)

Android: where are downloaded files saved?

Most devices have some form of emulated storage. if they support sd cards they are usually mounted to /sdcard (or some variation of that name) which is usually symlinked to to a directory in /storage like /storage/sdcard0 or /storage/0 sometimes the emulated storage is mounted to /sdcard and the actual path is something like /storage/emulated/legacy. You should be able to use to get the downloads directory. You are best off using the api calls to get directories. Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

Since the filesystems and sdcard support varies among devices.

see similar question for more info how to access downloads folder in android?

Usually the DownloadManager handles downloads and the files are then accessed by requesting the file's uri fromthe download manager using a file id to get where file was places which would usually be somewhere in the sdcard/ real or emulated since apps can only read data from certain places on the filesystem outside of their data directory like the sdcard

PostgreSQL column 'foo' does not exist

In my case when i run select query it works and gives desired data. But when i run query like

select * from users where email = "[email protected]"

It shows this error

ERROR:  column "[email protected]" does not exist
LINE 2: select * from users where email = "[email protected]...
                                          ^
SQL state: 42703
Character: 106

Then i use single quotes instead of double quotes for match condition, it works. for ex.

select * from users where email = '[email protected]'

How can I specify the required Node.js version in package.json?

There's another, simpler way to do this:

  1. npm install Node@8 (saves Node 8 as dependency in package.json)
  2. Your app will run using Node 8 for anyone - even Yarn users!

This works because node is just a package that ships node as its package binary. It just includes as node_module/.bin which means it only makes node available to package scripts. Not main shell.

See discussion on Twitter here: https://twitter.com/housecor/status/962347301456015360

What is the difference between DBMS and RDBMS?

DBMS : Data Base Management System ..... for storage of data and efficient retrieval of data. Eg: Foxpro

1)A DBMS has to be persistent (it should be accessible when the program created the data donot exist or even the application that created the data restarted).

2) DBMS has to provide some uniform methods independent of a specific application for accessing the information that is stored.

3)DBMS does not impose any constraints or security with regard to data manipulation. It is user or the programmer responsibility to ensure the ACID PROPERTY of the database

4)In DBMS Normalization process will not be present

5)In dbms no relationship concept

6)It supports Single User only

7)It treats Data as Files internally

8)It supports 3 rules of E.F.CODD out off 12 rules

9)It requires low Software and Hardware Requirements.

FoxPro, IMS are Examples

RDBMS: Relational Data Base Management System

.....the database which is used by relations(tables) to acquire information retrieval Eg: oracle, SQL..,

1)RDBMS is based on relational model, in which data is represented in the form of relations, with enforced relationships between the tables.

2)RDBMS defines the integrity constraint for the purpose of holding ACID PROPERTY.

3)In RDBMS, normalization process will be present to check the database table cosistency

4)RDBMS helps in recovery of the database in case of loss of data

5)It is used to establish the relationship concept between two database objects, i.e, tables

6)It supports multiple users

7)It treats data as Tables internally

8)It supports minimum 6 rules of E.F.CODD

9)It requires High software and hardware

CSS Margin: 0 is not setting to 0

Try

html, body{
  margin:0 !important;
  padding:0 !important;
}

How to tell if node.js is installed or not

Ctrl + R - to open the command line and then writes:

node -v

How to delete object?

You cannot delete an managed object in C# . That's why is called MANAGED language. So you don't have to troble yourself with delete (just like in c++).

It is true that you can set it's instance to null. But that is not going to help you that much because you have no control of your GC (Garbage collector) to delete some objects apart from Collect. And this is not what you want because this will delete all your collection from a generation.

So how is it done then ? So : GC searches periodically objects that are not used anymore and it deletes the object with an internal mechanism that should not concern you.

When you set an instance to null you just notify that your object has no referene anymore ant that could help CG to collect it faster !!!

The difference between the Runnable and Callable interfaces in Java

Runnable (vs) Callable comes into point when we are using Executer framework.

ExecutorService is a subinterface of Executor, which accepts both Runnable and Callable tasks.

Earlier Multi-Threading can be achieved using Interface RunnableSince 1.0, but here the problem is after completing the thread task we are unable to collect the Threads information. In-order to collect the data we may use Static fields.

Example Separate threads to collect each student data.

static HashMap<String, List> multiTasksData = new HashMap();
public static void main(String[] args) {
    Thread t1 = new Thread( new RunnableImpl(1), "T1" );
    Thread t2 = new Thread( new RunnableImpl(2), "T2" );
    Thread t3 = new Thread( new RunnableImpl(3), "T3" );

    multiTasksData.put("T1", new ArrayList() ); // later get the value and update it.
    multiTasksData.put("T2", new ArrayList() );
    multiTasksData.put("T3", new ArrayList() );
}

To resolve this problem they have introduced Callable<V>Since 1.5 which returns a result and may throw an exception.

  • Single Abstract Method : Both Callable and Runnable interface have a single abstract method, which means they can be used in lambda expressions in java 8.

    public interface Runnable {
    public void run();
    }
    
    public interface Callable<Object> {
        public Object call() throws Exception;
    }
    

There are a few different ways to delegate tasks for execution to an ExecutorService.

  • execute(Runnable task):void crates new thread but not blocks main thread or caller thread as this method return void.
  • submit(Callable<?>):Future<?>, submit(Runnable):Future<?> crates new thread and blocks main thread when you are using future.get().

Example of using Interfaces Runnable, Callable with Executor framework.

class CallableTask implements Callable<Integer> {
    private int num = 0;
    public CallableTask(int num) {
        this.num = num;
    }
    @Override
    public Integer call() throws Exception {
        String threadName = Thread.currentThread().getName();
        System.out.println(threadName + " : Started Task...");

        for (int i = 0; i < 5; i++) {
            System.out.println(i + " : " + threadName + " : " + num);
            num = num + i;
            MainThread_Wait_TillWorkerThreadsComplete.sleep(1);
        }
        System.out.println(threadName + " : Completed Task. Final Value : "+ num);

        return num;
    }
}
class RunnableTask implements Runnable {
    private int num = 0;
    public RunnableTask(int num) {
        this.num = num;
    }
    @Override
    public void run() {
        String threadName = Thread.currentThread().getName();
        System.out.println(threadName + " : Started Task...");

        for (int i = 0; i < 5; i++) {
            System.out.println(i + " : " + threadName + " : " + num);
            num = num + i;
            MainThread_Wait_TillWorkerThreadsComplete.sleep(1);
        }
        System.out.println(threadName + " : Completed Task. Final Value : "+ num);
    }
}
public class MainThread_Wait_TillWorkerThreadsComplete {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        System.out.println("Main Thread start...");
        Instant start = java.time.Instant.now();

        runnableThreads();
        callableThreads();

        Instant end = java.time.Instant.now();
        Duration between = java.time.Duration.between(start, end);
        System.out.format("Time taken : %02d:%02d.%04d \n", between.toMinutes(), between.getSeconds(), between.toMillis()); 

        System.out.println("Main Thread completed...");
    }
    public static void runnableThreads() throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(4);
        Future<?> f1 = executor.submit( new RunnableTask(5) );
        Future<?> f2 = executor.submit( new RunnableTask(2) );
        Future<?> f3 = executor.submit( new RunnableTask(1) );

        // Waits until pool-thread complete, return null upon successful completion.
        System.out.println("F1 : "+ f1.get());
        System.out.println("F2 : "+ f2.get());
        System.out.println("F3 : "+ f3.get());

        executor.shutdown();
    }
    public static void callableThreads() throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(4);
        Future<Integer> f1 = executor.submit( new CallableTask(5) );
        Future<Integer> f2 = executor.submit( new CallableTask(2) );
        Future<Integer> f3 = executor.submit( new CallableTask(1) );

        // Waits until pool-thread complete, returns the result.
        System.out.println("F1 : "+ f1.get());
        System.out.println("F2 : "+ f2.get());
        System.out.println("F3 : "+ f3.get());

        executor.shutdown();
    }
}