Programs & Examples On #Arp

ARP is a protocol for resolution of network layer addresses such as IP into link layer addresses (such as MAC addresses). "arp" is also a command in Linux and Windows to manipulate the ARP cache.

Send a ping to each IP on a subnet

FOR /L %i in (1,1,254) DO PING 192.168.1.%i -n 1 -w 100 | for /f "tokens=3 delims=: " %j in ('find /i "TTL="') do echo %j>>IPsOnline.txt

DB query builder toArray() laravel 4

If you prefer to use Query Builder instead of Eloquent here is the solutions

$result = DB::table('user')->where('name',=,'Jhon')->get();

First Solution

$array = (array) $result;

Second Solution

$array = get_object_vars($result);

Third Solution

$array = json_decode(json_encode($result), true);

hope it may help

Disabling browser print options (headers, footers, margins) from page?

@page margin:0mm now works in Firefox 19.0a2 (2012-12-07).

Parse JSON with R

The function fromJSON() in RJSONIO, rjson and jsonlite don't return a simple 2D data.frame for complex nested json objects.

To overcome this you can use tidyjson. It takes in a json and always returns a data.frame. It is currently not availble in CRAN, you can get it here: https://github.com/sailthru/tidyjson

Update: tidyjson is now available in cran, you can install it directly using install.packages("tidyjson")

How can I kill a process by name instead of PID?

ps aux | grep processname | cut -d' ' -f7 | xargs kill -9 $

C# Collection was modified; enumeration operation may not execute

I suspect the error is caused by this:

foreach (KeyValuePair<int, int> kvp in rankings)

rankings is a dictionary, which is IEnumerable. By using it in a foreach loop, you're specifying that you want each KeyValuePair from the dictionary in a deferred manner. That is, the next KeyValuePair is not returned until your loop iterates again.

But you're modifying the dictionary inside your loop:

rankings[kvp.Key] = rankings[kvp.Key] + 4;

which isn't allowed...so you get the exception.

You could simply do this

foreach (KeyValuePair<int, int> kvp in rankings.ToArray())

Vertical dividers on horizontal UL menu

Quite and simple without any "having to specify the first element". CSS is more powerful than most think (e.g. the first-child:before is great!). But this is by far the cleanest and most proper way to do this, at least in my opinion it is.

#navigation ul
{
    margin: 0;
    padding: 0;
}

#navigation ul li
{
    list-style-type: none;
    display: inline;
}

#navigation li:not(:first-child):before {
    content: " | ";
}

Now just use a simple unordered list in HTML and it'll populate it for you. HTML should look like this:

<div id="navigation">
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">About Us</a></li>
        <li><a href="#">Support</a></li>
    </ul>
</div><!-- navigation -->

The result will be just like this:

HOME | ABOUT US | SUPPORT

Now you can indefinitely expand and never have to worry about order, changing links, or your first entry. It's all automated and works great!

Reorder HTML table rows using drag-and-drop

thanks to Jim Petkus that did gave me a wonderful answer . but i was trying to solve my own script not to changing it to another plugin . My main focus was not using an independent plugin and do what i wanted just by using the jquery core !

and guess what i did find the problem .

var title = $("em").attr("title");
$("div").text(title);

this is what i add to my script and the blew codes to my html part :

<td> <em title=\"$weight\">$weight</em></td>

and found each row $weight value

thanks again to Jim Petkus

In Perl, how to remove ^M from a file?

This one liner replaces all the ^M characters:

dos2unix <file-name>

You can call this from inside Perl or directly on your Unix prompt.

Python: PIP install path, what is the correct location for this and other addons?

Also, when you uninstall the package, the first item listed is the directory to the executable.

Adjust UILabel height depending on the text

Since sizeWithFont is deprecated I use this one instead.

this one get label specific attributes.

-(CGFloat)heightForLabel:(UILabel *)label withText:(NSString *)text{

    NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName:label.font}];
    CGRect rect = [attributedText boundingRectWithSize:(CGSize){label.frame.size.width, CGFLOAT_MAX}
                                           options:NSStringDrawingUsesLineFragmentOrigin
                                           context:nil];

    return ceil(rect.size.height);
}

Matplotlib scatter plot legend

Here's an easier way of doing this (source: here):

import matplotlib.pyplot as plt
from numpy.random import rand


fig, ax = plt.subplots()
for color in ['red', 'green', 'blue']:
    n = 750
    x, y = rand(2, n)
    scale = 200.0 * rand(n)
    ax.scatter(x, y, c=color, s=scale, label=color,
               alpha=0.3, edgecolors='none')

ax.legend()
ax.grid(True)

plt.show()

And you'll get this:

enter image description here

Take a look at here for legend properties

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

Exception clearly indicates the problem.

CompteDAOHib: No default constructor found

For spring to instantiate your bean, you need to provide a empty constructor for your class CompteDAOHib.

Exporting PDF with jspdf not rendering CSS

You can get the example of css implemented html to pdf conversion using jspdf on following link: JSFiddle Link

This is sample code for the jspdf html to pdf download.

$('#print-btn').click(() => {
    var pdf = new jsPDF('p','pt','a4');
    pdf.addHTML(document.body,function() {
        pdf.save('web.pdf');
    });
})

How to set image in imageview in android?

use the following code,

    iv.setImageResource(getResources().getIdentifier("apple", "drawable", getPackageName()));

Update R using RStudio

Just restart R Studio after installing the new version of R. To confirm you're on the new version, >version and you should see the new details.

How can I drop a table if there is a foreign key constraint in SQL Server?

Type this .... SET foreign_key_checks = 0;
delete your table then type SET foreign_key_checks = 1;

MySQL – Temporarily disable Foreign Key Checks or Constraints

Why doesn't JavaScript support multithreading?

Multi-threading with javascript is clearly possible using webworkers bring by HTML5.

Main difference between webworkers and a standard multi-threading environment is memory resources are not shared with the main thread, a reference to an object is not visible from one thread to another. Threads communicate by exchanging messages, it is therefore possible to implement a synchronzization and concurrent method call algorithm following an event-driven design pattern.

Many frameworks exists allowing to structure programmation between threads, among them OODK-JS, an OOP js framework supporting concurrent programming https://github.com/GOMServices/oodk-js-oop-for-js

Remove grid, background color, and top and right borders from ggplot2

I followed Andrew's answer, but I also had to follow https://stackoverflow.com/a/35833548 and set the x and y axes separately due to a bug in my version of ggplot (v2.1.0).

Instead of

theme(axis.line = element_line(color = 'black'))

I used

theme(axis.line.x = element_line(color="black", size = 2),
    axis.line.y = element_line(color="black", size = 2))

Configure Log4net to write to multiple files

Use below XML configuration to configure logs into two or more files:

<log4net>
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="logs\log.txt" />         
      <appendToFile value="true" /> 
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">           
        <conversionPattern value="%date [%thread] %level %logger - %message%newline" />
      </layout>
    </appender>
     <appender name="RollingLogFileAppender2" type="log4net.Appender.RollingFileAppender">
      <file value="logs\log1.txt" />         
      <appendToFile value="true" /> 
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">        
        <conversionPattern value="%date [%thread] %level %logger - %message%newline" />
      </layout>
    </appender>
    <root>
      <level value="All" />
      <appender-ref ref="RollingLogFileAppender" />
    </root>
     <logger additivity="false" name="RollingLogFileAppender2">
    <level value="All"/>
    <appender-ref ref="RollingLogFileAppender2" />
    </logger>
  </log4net>

Above XML configuration logs into two different files. To get specific instance of logger programmatically:

ILog logger = log4net.LogManager.GetLogger ("RollingLogFileAppender2");

You can append two or more appender elements inside log4net root element for logging into multiples files.

More info about above XML configuration structure or which appender is best for your application, read details from below links:

https://logging.apache.org/log4net/release/manual/configuration.html https://logging.apache.org/log4net/release/sdk/index.html

Switch case with fallthrough?

Try this:

case $VAR in
normal)
    echo "This doesn't do fallthrough"
    ;;
special)
    echo -n "This does "
    ;&
fallthrough)
    echo "fall-through"
    ;;
esac

How to solve : SQL Error: ORA-00604: error occurred at recursive SQL level 1

One possible explanation is a database trigger that fires for each DROP TABLE statement. To find the trigger, query the _TRIGGERS dictionary views:

select * from all_triggers
where trigger_type in ('AFTER EVENT', 'BEFORE EVENT')

disable any suspicious trigger with

   alter trigger <trigger_name> disable;

and try re-running your DROP TABLE statement

How to add text inside the doughnut chart using Chart.js?

@Cmyker, great solution for chart.js v2

One little enhancement: It makes sense to check for the appropriate canvas id, see the modified snippet below. Otherwise the text (i.e. 75%) is also rendered in middle of other chart types within the page.

  Chart.pluginService.register({
    beforeDraw: function(chart) {
      if (chart.canvas.id === 'doghnutChart') {
        let width = chart.chart.width,
            height = chart.chart.outerRadius * 2,
            ctx = chart.chart.ctx;

        rewardImg.width = 40;
        rewardImg.height = 40;
        let imageX = Math.round((width - rewardImg.width) / 2),
            imageY = (height - rewardImg.height ) / 2;

        ctx.drawImage(rewardImg, imageX, imageY, 40, 40);
        ctx.save();
      }
    }
  });

Since a legend (see: http://www.chartjs.org/docs/latest/configuration/legend.html) magnifies the chart height, the value for height should be obtained by the radius.

How to set tbody height with overflow scroll

In my case I wanted to have responsive table height instead of fixed height in pixels as the other answers are showing. To do that I used percentage of visible height property and overflow on div containing the table:

&__table-container {
  height: 70vh;
  overflow: scroll;
}

This way the table will expand along with the window being resized.

how to merge 200 csv files in Python

Let's say you have 2 csv files like these:

csv1.csv:

id,name
1,Armin
2,Sven

csv2.csv:

id,place,year
1,Reykjavik,2017
2,Amsterdam,2018
3,Berlin,2019

and you want the result to be like this csv3.csv:

id,name,place,year
1,Armin,Reykjavik,2017
2,Sven,Amsterdam,2018
3,,Berlin,2019

Then you can use the following snippet to do that:

import csv
import pandas as pd

# the file names
f1 = "csv1.csv"
f2 = "csv2.csv"
out_f = "csv3.csv"

# read the files
df1 = pd.read_csv(f1)
df2 = pd.read_csv(f2)

# get the keys
keys1 = list(df1)
keys2 = list(df2)

# merge both files
for idx, row in df2.iterrows():
    data = df1[df1['id'] == row['id']]

    # if row with such id does not exist, add the whole row
    if data.empty:
        next_idx = len(df1)
        for key in keys2:
            df1.at[next_idx, key] = df2.at[idx, key]

    # if row with such id exists, add only the missing keys with their values
    else:
        i = int(data.index[0])
        for key in keys2:
            if key not in keys1:
                df1.at[i, key] = df2.at[idx, key]

# save the merged files
df1.to_csv(out_f, index=False, encoding='utf-8', quotechar="", quoting=csv.QUOTE_NONE)

With the help of a loop you can achieve the same result for multiple files as it is in your case (200 csv files).

javascript date + 7 days

_x000D_
_x000D_
var date = new Date();_x000D_
date.setDate(date.getDate() + 7);_x000D_
_x000D_
console.log(date);
_x000D_
_x000D_
_x000D_

And yes, this also works if date.getDate() + 7 is greater than the last day of the month. See MDN for more information.

Simulate a specific CURL in PostMan

As mentioned in multiple answers above you can import the cURL in POSTMAN directly. But if URL is authorized (or is not working for some reason) ill suggest you can manually add all the data points as JSON in your postman body. take the API URL from the cURL.

for the Authorization part- just add an Authorization key and base 64 encoded string as value.

example:

curl -u rzp_test_26ccbdbfe0e84b:69b2e24411e384f91213f22a \ https://api.razorpay.com/v1/orders -X POST \ --data "amount=50000" \ --data "currency=INR" \ --data "receipt=Receipt #20" \ --data "payment_capture=1" https://api.razorpay.com/v1/orders

{ "amount": "5000", "currency": "INR", "receipt": "Receipt #20", "payment_capture": "1" }

Headers: Authorization:Basic cnpwX3Rlc3RfWEk5QW5TU0N3RlhjZ0Y6dURjVThLZ3JiQVVnZ3JNS***U056V25J where "cnpwX3Rlc3RfWEk5QW5TU0N3RlhjZ0Y6dURjVThLZ3JiQVVnZ3JNS***U056V25J" is the encoded form of "rzp_test_26ccbdbfe0e84b:69b2e24411e384f91213f22a"`

small tip: for encoding, you can easily go to your chrome console (right-click => inspect) and type : btoa("string you want to encode") ( or use postman basic authorization)

Do Facebook Oauth 2.0 Access Tokens Expire?

I don't know when exactly the tokens expire, but they do, otherwise there wouldn't be an option to give offline permissions.

Anyway, sometimes requiring the user to give offline permissions is an overkill. Depending on your needs, maybe it's enough that the token remains valid as long as the website is opened in the user's browser. For this there may be a simpler solution - relogging the user in periodically using an iframe: facebook auto re-login from cookie php

Worked for me...

Delete statement in SQL is very slow

Preventive Action

Check with the help of SQL Profiler for the root cause of this issue. There may be Triggers causing the delay in Execution. It can be anything. Don't forget to Select the Database Name and Object Name while Starting the Trace to exclude scanning unnecessary queries...

Database Name Filtering

Table/Stored Procedure/Trigger Name Filtering

Corrective Action

As you said your table contains 260,000 records...and IN Predicate contains six values. Now, each record is being search 260,000 times for each value in IN Predicate. Instead it should be the Inner Join like below...

Delete K From YourTable1 K
Inner Join YourTable2 T on T.id = K.id

Insert the IN Predicate values into a Temporary Table or Local Variable

Using module 'subprocess' with timeout

I added the solution with threading from jcollado to my Python module easyprocess.

Install:

pip install easyprocess

Example:

from easyprocess import Proc

# shell is not supported!
stdout=Proc('ping localhost').call(timeout=1.5).stdout
print stdout

Can I do a max(count(*)) in SQL?

create view sal as
select yr,count(*) as ct from
(select title,yr from movie m, actor a, casting c
where a.name='JOHN'
and a.id=c.actorid
and c.movieid=m.id)group by yr

-----VIEW CREATED-----

select yr from sal
where ct =(select max(ct) from sal)

YR 2013

Remove background drawable programmatically in Android

This helped me remove background color, hope it helps someone. setBackgroundColor(Color.TRANSPARENT)

Multiple Errors Installing Visual Studio 2015 Community Edition

None of the resolutions outlined in this question solved my issue. I posted a similar question and ended up having to open a support ticket with Microsoft to get it resolved. See my answer here if none of the other suggestions help: Error Installing Visual Studio 2015 Enterprise Update 1 with Team Explorer

Populating a razor dropdownlist from a List<object> in MVC

Instead of a List<UserRole>, you can let your Model contain a SelectList<UserRole>. Also add a property SelectedUserRoleId to store... well... the selected UserRole's Id value.

Fill up the SelectList, then in your View use:

@Html.DropDownListFor(x => x.SelectedUserRoleId, x.UserRole)

and you should be fine.

See also http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist(v=vs.108).aspx.

Remove spaces from a string in VB.NET

This will remove spaces only, matches the SQL functionality of rtrim(ltrim(myString))

Dim charstotrim() As Char = {" "c}
myString = myString .Trim(charstotrim) 

How to keep one variable constant with other one changing with row in excel

=(B0+4)/($A$0)

$ means keep same (press a few times F4 after typing A4 to flip through combos quick!)

PHP Array to JSON Array using json_encode();

A common use of JSON is to read data from a web server, and display the data in a web page.

This chapter will teach you how to exchange JSON data between the client and a PHP server.

PHP has some built-in functions to handle JSON.

Objects in PHP can be converted into JSON by using the PHP function json_encode():

_x000D_
_x000D_
<?php_x000D_
$myObj->name = "John";_x000D_
$myObj->age = 30;_x000D_
$myObj->city = "New York";_x000D_
_x000D_
$myJSON = json_encode($myObj);_x000D_
_x000D_
echo $myJSON;_x000D_
?>
_x000D_
_x000D_
_x000D_

How to get URL parameters with Javascript?

function getURLParameter(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}

So you can use:

myvar = getURLParameter('myvar');

Set EditText cursor color

Use this

android:textCursorDrawable="@color/white"

SQL INSERT INTO from multiple tables

I would suggest instead of creating a new table, you just use a view that combines the two tables, this way if any of the data in table 1 or table 2 changes, you don't need to update the third table:

CREATE VIEW dbo.YourView
AS
    SELECT  t1.Name, t1.Age, t1.Sex, t1.City, t1.ID, t2.Number
    FROM    Table1 t1
            INNER JOIN Table2 t2
                ON t1.ID = t2.ID;

If you could have records in one table, and not in the other, then you would need to use a full join:

CREATE VIEW dbo.YourView
AS
    SELECT  t1.Name, t1.Age, t1.Sex, t1.City, ID = ISNULL(t1.ID, t2.ID), t2.Number
    FROM    Table1 t1
            FULL JOIN Table2 t2
                ON t1.ID = t2.ID;

If you know all records will be in table 1 and only some in table 2, then you should use a LEFT JOIN:

CREATE VIEW dbo.YourView
AS
    SELECT  t1.Name, t1.Age, t1.Sex, t1.City, t1.ID, t2.Number
    FROM    Table1 t1
            LEFT JOIN Table2 t2
                ON t1.ID = t2.ID;

If you know all records will be in table 2 and only some in table 2 then you could use a RIGHT JOIN

CREATE VIEW dbo.YourView
AS
    SELECT  t1.Name, t1.Age, t1.Sex, t1.City, t2.ID, t2.Number
    FROM    Table1 t1
            RIGHT JOIN Table2 t2
                ON t1.ID = t2.ID;

Or just reverse the order of the tables and use a LEFT JOIN (I find this more logical than a right join but it is personal preference):

CREATE VIEW dbo.YourView
AS
    SELECT  t1.Name, t1.Age, t1.Sex, t1.City, t2.ID, t2.Number
    FROM    Table2 t2
            LEFT JOIN Table1 t1
                ON t1.ID = t2.ID;

addEventListener in Internet Explorer

Here's something for those who like beautiful code.

function addEventListener(obj,evt,func){
    if ('addEventListener' in window){
        obj.addEventListener(evt,func, false);
    } else if ('attachEvent' in window){//IE
        obj.attachEvent('on'+evt,func);
    }
}

Shamelessly stolen from Iframe-Resizer.

Omitting one Setter/Getter in Lombok

with lombak 1.8.12, this worked for me

@Getter(value = lombok.AccessLevel.NONE)
@Setter(value = lombok.AccessLevel.NONE)

private int password;

Get viewport/window height in ReactJS

I found a simple combo of QoP and speckledcarp's answer using React Hooks and resizing features, with slightly less lines of code:

const [width, setWidth]   = useState(window.innerWidth);
const [height, setHeight] = useState(window.innerHeight);
const updateDimensions = () => {
    setWidth(window.innerWidth);
    setHeight(window.innerHeight);
}
useEffect(() => {
    window.addEventListener("resize", updateDimensions);
    return () => window.removeEventListener("resize", updateDimensions);
}, []);

Oh yeah make sure that the resize event is in double quotes, not single. That one got me for a bit ;)

Javascript: How to loop through ALL DOM elements on a page?

Andy E. gave a good answer.

I would add, if you feel to select all the childs in some special selector (this need happened to me recently), you can apply the method "getElementsByTagName()" on any DOM object you want.

For an example, I needed to just parse "visual" part of the web page, so I just made this

var visualDomElts = document.body.getElementsByTagName('*');

This will never take in consideration the head part.

Why SQL Server throws Arithmetic overflow error converting int to data type numeric?

NUMERIC(3,2) means: 3 digits in total, 2 after the decimal point. So you only have a single decimal before the decimal point.

Try NUMERIC(5,2) - three before, two after the decimal point.

How to get table cells evenly spaced?

In your CSS file:

.TableHeader { width: 100px; }

This will set all of the td tags below each header to 100px. You can also add a width definition (in the markup) to each individual th tag, but the above solution would be easier.

jQuery ui dialog change title after load-callback

Using dialog methods:

$('.selectorUsedToCreateTheDialog').dialog('option', 'title', 'My New title');

Or directly, hacky though:

$("span.ui-dialog-title").text('My New Title'); 

For future reference, you can skip google with jQuery. The jQuery API will answer your questions most of the time. In this case, the Dialog API page. For the main library: http://api.jquery.com

Should MySQL have its timezone set to UTC?

The pros and cons are pretty much identical.It depends on whether you want this or not.

Be careful, if MySQL timezone differs from your system time (for instance PHP), comparing the time or printing to the user will involve some tinkering.

Laravel - Forbidden You don't have permission to access / on this server

On public/.htaccess edit to

<IfModule mod_rewrite.c>
 <IfModule mod_negotiation.c>
              Options -MultiViews
          </IfModule>

          RewriteEngine On

          # Redirect Trailing Slashes If Not A Folder...
          RewriteCond %{REQUEST_FILENAME} !-d
          RewriteCond %{REQUEST_URI} (.+)/$
          RewriteRule ^ %1 [L,R=301]

          # Handle Front Controller...
          RewriteCond %{REQUEST_FILENAME} !-d
          RewriteCond %{REQUEST_FILENAME} !-f
          RewriteRule ^ index.php [L]

          # Handle Authorization Header
          RewriteCond %{HTTP:Authorization} .
          RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

In the root of the project add file

Procfile

File content

web: vendor/bin/heroku-php-apache2 public/

Reload the project to Heroku

bash
heroku login
cd my-project/
git init
heroku git:remote -a my project
git add .
git commit -am "make it better"
git push heroku master
heroku open

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

The solution is simple, but temporary...

Note that if you run an npm install or a yarn install you need to change the code again!

So, how can we run this automatically?

Permanent Solution

To do this "automagically" after installing your node modules, you can use patch-package.

  1. Fix the metro-config file, solving the error:

The file appears in \node_modules\metro-config\src\defaults\blacklist.js.

Edit from:

var sharedBlacklist = [
  /node_modules[/\\]react[/\\]dist[/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

To:

var sharedBlacklist = [
  /node_modules[\/\\]react[\/\\]dist[\/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];
  1. Then, generate a permanent patch file:

npx patch-package metro-config

  1. In your package.json trigger the patch:
"scripts": {
+  "postinstall": "npx patch-package"
}

All done! Now this patch will be made at every npm install / yarn install.

Thanks to https://github.com/ds300/patch-package

How to get numeric position of alphabets in java?

just logic I can suggest take two arrays.

one is Char array

and another is int array.

convert ur input string to char array,get the position of char from char and int array.

dont expect source code here

How to force a WPF binding to refresh?

I was fetching data from backend and updated the screen with just one line of code. It worked. Not sure, why we need to implement Interface. (windows 10, UWP)

    private void populateInCurrentScreen()
    {
        (this.FindName("Dets") as Grid).Visibility = Visibility.Visible;
        this.Bindings.Update();
    }

why is plotting with Matplotlib so slow?

Matplotlib makes great publication-quality graphics, but is not very well optimized for speed. There are a variety of python plotting packages that are designed with speed in mind:

How to generate an entity-relationship (ER) diagram using Oracle SQL Developer

There is a companion tool called Oracle Data Modeler that you could take a look at. There are online demos available at the site that will get you started. It used to be an added cost item, but I noticed that once again it's free.

From the Data Modeler overview page:

SQL Developer Data Modeler is a free data modeling and design tool, proving a full spectrum of data and database modeling tools and utilities, including modeling for Entity Relationship Diagrams (ERD), Relational (database design), Data Type and Multi-dimensional modeling, with forward and reverse engineering and DDL code generation. The Data Modeler imports from and exports to a variety of sources and targets, provides a variety of formatting options and validates the models through a predefined set of design rules.

Add new value to an existing array in JavaScript

This has nothing to do with jQuery, just JavaScript in general.

To create an array in JavaScript:

var a = [];

Or:

var a = ['value1', 'value2', 'value3'];

To append values on the end of existing array:

a.push('value4');

To create a new array, you should really use [] instead of new Array() for the following reasons:

  • new Array(1, 2) is equivalent to [1, 2], but new Array(1) is not equivalent to [1]. Rather the latter is closer to [undefined], since a single integer argument to the Array constructor indicates the desired array length.
  • Array, just like any other built-in JavaScript class, is not a keyword. Therefore, someone could easily define Array in your code to do something other than construct an array.

Import error: No module name urllib2

Python 3:

import urllib.request

wp = urllib.request.urlopen("http://google.com")
pw = wp.read()
print(pw)

Python 2:

import urllib
import sys

wp = urllib.urlopen("http://google.com")
for line in wp:
    sys.stdout.write(line)

While I have tested both the Codes in respective versions.

What is the command to exit a Console application in C#?

You can use Environment.Exit(0) and Application.Exit.

Environment.Exit(): terminates this process and gives the underlying operating system the specified exit code.

connecting to mysql server on another PC in LAN

Since you have mysql on your local computer, you do not need to bother with the IP address of the machine. Just use localhost:

mysql -u user -p

or

mysql -hlocalhost -u user -p

If you cannot login with this, you must find out what usernames (user@host) exist in the MySQL Server locallly. Here is what you do:

Step 01) Startup mysql so that no passwords are require no passwords and denies TCP/IP connections

service mysql restart --skip-grant-tables --skip-networking

Keep in mind that standard SQL for adding users, granting and revoking privs are disabled.

Step 02) Show users and hosts

select concat(''',user,'''@''',host,'''') userhost,password from mysql.user;

Step 03) Check your password to make sure it works

select user,host from mysql.user where password=password('YourMySQLPassword');

If your password produces no output for this query, you have a bad password.

If your password produces output for this query, look at the users and hosts. If your host value is '%', your should be able to connect from anywhere. If your host is 'localhost', you should be able to connect locally.

Make user you have 'root'@'localhost' defined.

Once you have done what is needed, just restart mysql normally

service mysql restart

If you are able to connect successfully on the macbook, run this query:

SELECT USER(),CURRENT_USER();

USER() reports how you attempted to authenticate in MySQL

CURRENT_USER() reports how you were allowed to authenticate in MySQL

Let us know what happens !!!

UPDATE 2012-02-13 20:47 EDT

Login to the remote server and repeat Step 1-3

See if any user allows remote access (i.e, host in mysql.user is '%'). If you do not, then add 'user'@'%' to mysql.user.

Oracle - Why does the leading zero of a number disappear when converting it TO_CHAR

Below format try if number is like

ex 1 suppose number like 10.1 if apply below format it will be come as 10.10

ex 2 suppose number like .02 if apply below format it will be come as 0.02

ex 3 suppose number like 0.2 if apply below format it will be come as 0.20

to_char(round(to_number(column_name)/10000000,2),'999999999990D99') as column_name

How do I find out where login scripts live?

The default location for logon scripts is the netlogon share of a domain controller. On the server this is located:

%SystemRoot%'SYSVOL'sysvol''scripts

It can presumably be changes from this default but I've never met anyone that had a reason to.

To get list of domain controllers programatically see this article: http://www.microsoft.com/technet/scriptcenter/resources/qanda/dec04/hey1216.mspx

Manipulating an Access database from Java without ODBC

UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.

 

Option 1: Using Maven

If your project uses Maven you can simply include UCanAccess via the following coordinates:

groupId: net.sf.ucanaccess
artifactId: ucanaccess

The following is an excerpt from pom.xml, you may need to update the <version> to get the most recent release:

  <dependencies>
    <dependency>
        <groupId>net.sf.ucanaccess</groupId>
        <artifactId>ucanaccess</artifactId>
        <version>4.0.4</version>
    </dependency>
  </dependencies>

 

Option 2: Manually adding the JARs to your project

As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:

UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)

Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like

ucanaccess-4.0.1.jar  
  /lib/
    commons-lang-2.6.jar  
    commons-logging-1.1.1.jar  
    hsqldb.jar  
    jackcess-2.1.6.jar

All you need to do is add all five (5) JARs to your project.

NOTE: Do not add loader/ucanload.jar to your build path if you are adding the other five (5) JAR files. The UcanloadDriver class is only used in special circumstances and requires a different setup. See the related answer here for details.

Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path.... Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this

BuildPath.png

NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.

nbAddJar.png

After adding all five (5) JAR files the "Libraries" folder should look something like this:

nbLibraries.png

IntelliJ IDEA: Choose File > Project Structure... from the main menu. In the "Libraries" pane click the "Add" (+) button and add the five (5) JAR files. Once that is done the project should look something like this:

IntelliJ.png

 

That's it!

Now "U Can Access" data in .accdb and .mdb files using code like this

// assumes...
//     import java.sql.*;
Connection conn=DriverManager.getConnection(
        "jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
    System.out.println(rs.getString(1));
}

 

Disclosure

At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.

operator << must take exactly one argument

A friend function is not a member function, so the problem is that you declare operator<< as a friend of A:

 friend ostream& operator<<(ostream&, A&);

then try to define it as a member function of the class logic

 ostream& logic::operator<<(ostream& os, A& a)
          ^^^^^^^

Are you confused about whether logic is a class or a namespace?

The error is because you've tried to define a member operator<< taking two arguments, which means it takes three arguments including the implicit this parameter. The operator can only take two arguments, so that when you write a << b the two arguments are a and b.

You want to define ostream& operator<<(ostream&, const A&) as a non-member function, definitely not as a member of logic since it has nothing to do with that class!

std::ostream& operator<<(std::ostream& os, const A& a)
{
  return os << a.number;
}

Jquery post, response in new window

If you dont need a feedback about the requested data and also dont need any interactivity between the opener and the popup, you can post a hidden form into the popup:

Example:

<form method="post" target="popup" id="formID" style="display:none" action="https://example.com/barcode/generate" >
  <input type="hidden" name="packing_slip" value="35592" />
  <input type="hidden" name="reference" value="0018439" />
  <input type="hidden" name="total_boxes" value="1" />
</form>
<script type="text/javascript">
window.open('about:blank','popup','width=300,height=200')
document.getElementById('formID').submit();
</script>

Otherwise you could use jsonp. But this works only, if you have access to the other Server, because you have to modify the response.

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

The solution to this problem is very simple...

If you don't have Ant build file then generate it. In Eclipse you can easily create a Ant file.

Refer to the link to create Ant build file [http://www.codejava.net/ides/eclipse/how-to-create-ant-build-file-for-existing-java-project-in-eclipse].

Now follow the given steps:

1) Add your Ant build file in Ant view that is in view window.

2) right click on your Ant build file and select Run As and the second option in that "Ant Build".

3) Now a dialog box will open with various options and tabs.

4) Select the JRE tab.

5) You will see three radio buttons and they will be having JRE or JDK selected as an option.

6) Look carefully if the radio button options are having JRE as selected then change it to JDK.

7) Click apply.

That's it...!!!

Best way to do multiple constructors in PHP

public function __construct() {
    $parameters = func_get_args();
    ...
}

$o = new MyClass('One', 'Two', 3);

Now $paramters will be an array with the values 'One', 'Two', 3.

Edit,

I can add that

func_num_args()

will give you the number of parameters to the function.

Launching Spring application Address already in use

image of Spring Tool Suite and stop application button

In my case looking in the servers window only showed a tomcat server that I had never used for this project. My SpringBoot project used an embedded tomcat server and it did not stop when my application finished. This button which I indicate with a red arrow will stop the application and the Tomcat server so next time I run the application I will not get the error that an Instance of Tomcat is already running on port 8080.

actual error messages:

Verify the connector's configuration, identify and stop any process that's listening on port 8080, or configure this application to listen on another port.

Caused by: java.net.BindException: Address already in use Caused by: org.apache.catalina.LifecycleException: service.getName(): "Tomcat"; Protocol handler start failed

I will now be looking into a way to shut down all services on completion of my SpringBoot Consuming Rest application in this tutorial https://spring.io/guides/gs/consuming-rest/

spring-boot

Could not load file or assembly '***.dll' or one of its dependencies

An easier way to determine what dependencies a native DLL has is to use Dependency Walker - http://www.dependencywalker.com/

I analysed the native DLL and discovered that it depended on MSVCR120.DLL and MSVCP120.DLL, both of which were not installed on my staging server in the System32 directory. I installed the C++ runtime on my staging server and the issue was resolved.

Using a PHP variable in a text input value = statement

I have been doing PHP for my project, and I can say that the following code works for me. You should try it.

echo '<input type = "text" value = '.$idtest.'>'; 

Error during SSL Handshake with remote server

The comment by MK pointed me in the right direction.

In the case of Apache 2.4 and up, there are different defaults and a new directive.

I am running Apache 2.4.6, and I had to add the following directives to get it working:

SSLProxyEngine on
SSLProxyVerify none 
SSLProxyCheckPeerCN off
SSLProxyCheckPeerName off
SSLProxyCheckPeerExpire off

python max function using 'key' and lambda expression

lambda is an anonymous function, it is equivalent to:

def func(p):
   return p.totalScore     

Now max becomes:

max(players, key=func)

But as def statements are compound statements they can't be used where an expression is required, that's why sometimes lambda's are used.

Note that lambda is equivalent to what you'd put in a return statement of a def. Thus, you can't use statements inside a lambda, only expressions are allowed.


What does max do?

max(a, b, c, ...[, key=func]) -> value

With a single iterable argument, return its largest item. With two or more arguments, return the largest argument.

So, it simply returns the object that is the largest.


How does key work?

By default in Python 2 key compares items based on a set of rules based on the type of the objects (for example a string is always greater than an integer).

To modify the object before comparison, or to compare based on a particular attribute/index, you've to use the key argument.

Example 1:

A simple example, suppose you have a list of numbers in string form, but you want to compare those items by their integer value.

>>> lis = ['1', '100', '111', '2']

Here max compares the items using their original values (strings are compared lexicographically so you'd get '2' as output) :

>>> max(lis)
'2'

To compare the items by their integer value use key with a simple lambda:

>>> max(lis, key=lambda x:int(x))  # compare `int` version of each item
'111'

Example 2: Applying max to a list of tuples.

>>> lis = [(1,'a'), (3,'c'), (4,'e'), (-1,'z')]

By default max will compare the items by the first index. If the first index is the same then it'll compare the second index. As in my example, all items have a unique first index, so you'd get this as the answer:

>>> max(lis)
(4, 'e')

But, what if you wanted to compare each item by the value at index 1? Simple: use lambda:

>>> max(lis, key = lambda x: x[1])
(-1, 'z')

Comparing items in an iterable that contains objects of different type:

List with mixed items:

lis = ['1','100','111','2', 2, 2.57]

In Python 2 it is possible to compare items of two different types:

>>> max(lis)  # works in Python 2
'2'
>>> max(lis, key=lambda x: int(x))  # compare integer version of each item
'111'

But in Python 3 you can't do that any more:

>>> lis = ['1', '100', '111', '2', 2, 2.57]
>>> max(lis)
Traceback (most recent call last):
  File "<ipython-input-2-0ce0a02693e4>", line 1, in <module>
    max(lis)
TypeError: unorderable types: int() > str()

But this works, as we are comparing integer version of each object:

>>> max(lis, key=lambda x: int(x))  # or simply `max(lis, key=int)`
'111'

How to stick text to the bottom of the page?

You might want to put the absolutely aligned div in a relatively aligned container - this way it will still be contained into the container rather than the browser window.

<div style="position: relative;background-color: blue; width: 600px; height: 800px;">    

    <div style="position: absolute; bottom: 5px; background-color: green">
    TEST (C) 2010
    </div>
</div>

What does "to stub" mean in programming?

Stub is a function definition that has correct function name, the correct number of parameters and produces dummy result of the correct type.

It helps to write the test and serves as a kind of scaffolding to make it possible to run the examples even before the function design is complete

Sharing a variable between multiple different threads

You can use lock variables "a" and "b" and synchronize them for locking the "critical section" in reverse order. Eg. Notify "a" then Lock "b" ,"PRINT", Notify "b" then Lock "a".

Please refer the below the code :

public class EvenOdd {

    static int a = 0;

    public static void main(String[] args) {

        EvenOdd eo = new EvenOdd();

        A aobj = eo.new A();
        B bobj = eo.new B();

        aobj.a = Lock.lock1;
        aobj.b = Lock.lock2;

        bobj.a = Lock.lock2;
        bobj.b = Lock.lock1;

        Thread t1 = new Thread(aobj);
        Thread t2 = new Thread(bobj);

        t1.start();
        t2.start();
    }

    static class Lock {
        final static Object lock1 = new Object();
        final static Object lock2 = new Object();
    }

    class A implements Runnable {

        Object a;
        Object b;

        public void run() {
            while (EvenOdd.a < 10) {
                try {
                    System.out.println(++EvenOdd.a + " A ");
                    synchronized (a) {
                        a.notify();
                    }
                    synchronized (b) {
                        b.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    class B implements Runnable {

        Object a;
        Object b;

        public void run() {
            while (EvenOdd.a < 10) {

                try {
                    synchronized (b) {
                        b.wait();
                        System.out.println(++EvenOdd.a + " B ");
                    }
                    synchronized (a) {
                        a.notify();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

OUTPUT :

1 A 
2 B 
3 A 
4 B 
5 A 
6 B 
7 A 
8 B 
9 A 
10 B 

Use Font Awesome Icons in CSS

#content h2:before {
    content: "\f055";
    font-family: FontAwesome;
    left:0;
    position:absolute;
    top:0;
}

Example Link: https://codepen.io/bungeedesign/pen/XqeLQg

Get Icon code from: https://fontawesome.com/cheatsheet?from=io

Removing carriage return and new-line from the end of a string in c#

This will trim off any combination of carriage returns and newlines from the end of s:

s = s.TrimEnd(new char[] { '\r', '\n' });

Edit: Or as JP kindly points out, you can spell that more succinctly as:

s = s.TrimEnd('\r', '\n');

facebook Uncaught OAuthException: An active access token must be used to query information about the current user

So I had the same issue, but it was because I was saving the access token but not using it. It could be because I'm super sleepy because of due dates, or maybe I just didn't think about it! But in case anyone else is in the same situation:

When I log in the user I save the access token:

$facebook = new Facebook(array(
    'appId' => <insert the app id you get from facebook here>,
    'secret' => <insert the app secret you get from facebook here>
));

$accessToken = $facebook->getAccessToken();
//save the access token for later

Now when I make requests to facebook I just do something like this:

$facebook = new Facebook(array(
    'appId' => <insert the app id you get from facebook here>,
    'secret' => <insert the app secret you get from facebook here>
));

$facebook->setAccessToken($accessToken);
$facebook->api(... insert own code here ...)

Is it possible to Turn page programmatically in UIPageViewController?

As @samwize pointed out, the way of paginating is by using

setViewControllers:array

Here's the way I did it: I have my datasource and the delegate separate. You can call this method and only change the "next" view. Previously you have to apply the paging rules. That is, you have to check direction and the next controller. If you use that method with your custom datasource the array of controllers that you're displaying won't change (since you'll use a custom array on a NSObject subclass).

Using your own datasource the method just sets a new view (with specific direction). Since you will still controll the pages that will display when normally swiping.

Converting a date in MySQL from string field

STR_TO_DATE allows you to do this, and it has a format argument.

How to integrate sourcetree for gitlab

It worked for me, but only with https link in repository setting (Repository => Repository Settings). You need to change setting to:

URL / path: https://**********.com/username/project.git
Host Type - Stash
Host Root URL - your root URL to GitLab (example:https://**********.com/) 
Username - leave blank

or in some cases if you have ssh url like:

[email protected]:USER/REPOSITORY.git

and your email like:

[email protected]

then this settings should be work:

URL / path: https://test%[email protected]:USER/REPOSITORY.git

Remove Sub String by using Python

import re
re.sub('<.*?>', '', string)
"i think mabe 124 + but I don't have a big experience it just how I see it in my eyes fun stuff"

The re.sub function takes a regular expresion and replace all the matches in the string with the second parameter. In this case, we are searching for all tags ('<.*?>') and replacing them with nothing ('').

The ? is used in re for non-greedy searches.

More about the re module.

What's the best way to dedupe a table?

delete from yourTable 
where Id not in (
    select min(id) 
    from yourTable
    group by <Unique Columns>
)

where id is whatever is your unique id in the table. (Could be customerNumber or whatever)

If you don't have a Unique Id, you can add one (every SQL table should already have Id as first column, but

ALTER TABLE yourTable
ADD Id int identity(1,1)

Do your delete (above) and then drop the column.

Better than creating a whole new table, or any of the other cryptic stuff I've seen. Note, pretty much the same as in a comment here, but this is what I've done for years.

VBA ADODB excel - read data from Recordset

I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.

Set cn = CreateObject("ADODB.Connection")
With cn
 .Provider = "Microsoft.Jet.OLEDB.4.0"
  .ConnectionString = "Data Source=D:\test.xls " & _
  ";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
  For i = 0 To rs.Fields.Count - 1
    Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
    strNaam = rs.Fields(0).Value
  Next
  rs.MoveNext
Loop
rs.Close

There are other ways, depending on what you want to do, such as GetString (GetString Method Description).

What is the Windows version of cron?

The closest equivalent are the Windows Scheduled Tasks (Control Panel -> Scheduled Tasks), though they are a far, far cry from cron.

The biggest difference (to me) is that they require a user to be logged into the Windows box, and a user account (with password and all), which makes things a nightmare if your local security policy requires password changes periodically. I also think it is less flexible than cron as far as setting intervals for items to run.

Dynamic function name in javascript?

You was near:

_x000D_
_x000D_
this["instance_" + a] = function () {...};
_x000D_
_x000D_
_x000D_

{...};

SQL Server Operating system error 5: "5(Access is denied.)"

I had this problem. Just run SQL Server as administrator

Basic authentication with fetch?

You are missing a space between Basic and the encoded username and password.

headers.set('Authorization', 'Basic ' + base64.encode(username + ":" + password));

Echoing the last command run in Bash?

I was able to achieve this by using set -x in the main script (which makes the script print out every command that is executed) and writing a wrapper script which just shows the last line of output generated by set -x.

This is the main script:

#!/bin/bash
set -x
echo some command here
echo last command

And this is the wrapper script:

#!/bin/sh
./test.sh 2>&1 | grep '^\+' | tail -n 1 | sed -e 's/^\+ //'

Running the wrapper script produces this as output:

echo last command

Broadcast Receiver within a Service

as your service is already setup, simply add a broadcast receiver in your service:

private final BroadcastReceiver receiver = new BroadcastReceiver() {
   @Override
   public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
      if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
        //action for sms received
      }
      else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){
           //action for phone state changed
      }     
   }
};

in your service's onCreate do this:

IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter.addAction("your_action_strings"); //further more
filter.addAction("your_action_strings"); //further more

registerReceiver(receiver, filter);

and in your service's onDestroy:

unregisterReceiver(receiver);

and you are good to go to receive broadcast for what ever filters you mention in onCreate. Make sure to add any permission if required. for e.g.

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

How do I set combobox read-only or user cannot write in a combo box only can select the given items?

Just change the DropDownStyle to DropDownList. Or if you want it completely read only you can set Enabled = false, or if you don't like the look of that I sometimes have two controls, one readonly textbox and one combobox and then hide the combo and show the textbox if it should be completely readonly and vice versa.

Class vs. static method in JavaScript

Javascript has no actual classes rather it uses a system of prototypal inheritance in which objects 'inherit' from other objects via their prototype chain. This is best explained via code itself:

_x000D_
_x000D_
function Foo() {};_x000D_
// creates a new function object_x000D_
_x000D_
Foo.prototype.talk = function () {_x000D_
    console.log('hello~\n');_x000D_
};_x000D_
// put a new function (object) on the prototype (object) of the Foo function object_x000D_
_x000D_
var a = new Foo;_x000D_
// When foo is created using the new keyword it automatically has a reference _x000D_
// to the prototype property of the Foo function_x000D_
_x000D_
// We can show this with the following code_x000D_
console.log(Object.getPrototypeOf(a) === Foo.prototype); _x000D_
_x000D_
a.talk(); // 'hello~\n'_x000D_
// When the talk method is invoked it will first look on the object a for the talk method,_x000D_
// when this is not present it will look on the prototype of a (i.e. Foo.prototype)_x000D_
_x000D_
// When you want to call_x000D_
// Foo.talk();_x000D_
// this will not work because you haven't put the talk() property on the Foo_x000D_
// function object. Rather it is located on the prototype property of Foo._x000D_
_x000D_
// We could make it work like this:_x000D_
Foo.sayhi = function () {_x000D_
    console.log('hello there');_x000D_
};_x000D_
_x000D_
Foo.sayhi();_x000D_
// This works now. However it will not be present on the prototype chain _x000D_
// of objects we create out of Foo
_x000D_
_x000D_
_x000D_

JQuery Bootstrap Multiselect plugin - Set a value as selected in the multiselect dropdown

This is what worked from me using an array as input. First uncheck all options, then click on the chosen options using jquery

var dimensions = ["Dates","Campaigns","Placements"];

$(".input-dimensions").multiselect("uncheckAll");

for( var dim in dimensions) {
  $(".input-dimensions").multiselect("widget")
    .find(":checkbox[value='" + dimensions[dim] + "']").click();
}

Creating a copy of an object in C#

There's already a question about this, you could perhaps read it

Deep cloning objects

There's no Clone() method as it exists in Java for example, but you could include a copy constructor in your clases, that's another good approach.

class A
{
  private int attr

  public int Attr
  {
     get { return attr; }
     set { attr = value }
  }

  public A()
  {
  }

  public A(A p)
  {
     this.attr = p.Attr;
  }  
}

This would be an example, copying the member 'Attr' when building the new object.

Autocompletion of @author in Intellij

For Intellij IDEA Community 2019.1 you will need to follow these steps :

File -> New -> Edit File Templates.. -> Class -> /* Created by ${USER} on ${DATE} */

Why GDB jumps unpredictably between lines and prints variables as "<value optimized out>"?

When debugging optimized programs (which may be necessary if the bug doesn't show up in debug builds), you often have to understand assembly compiler generated.

In your particular case, return value of cpnd_find_exact_ckptinfo will be stored in the register which is used on your platform for return values. On ix86, that would be %eax. On x86_64: %rax, etc. You may need to google for '[your processor] procedure calling convention' if it's none of the above.

You can examine that register in GDB and you can set it. E.g. on ix86:

(gdb) p $eax
(gdb) set $eax = 0 

Difference between web server, web container and application server

The basic idea of Servlet container is using Java to dynamically generate the web page on the server side using Servlets and JSP. So servlet container is essentially a part of a web server that interacts with the servlets.

Unzip All Files In A Directory

Just put in some quotes to escape the wildcard:

unzip "*.zip"

How to Read from a Text File, Character by Character in C++

There is no reason not to use C <stdio.h> in C++, and in fact it is often the optimal choice.

#include <stdio.h>

int
main()  // (void) not necessary in C++
{
    int c;
    while ((c = getchar()) != EOF) {
        // do something with 'c' here
    }
    return 0; // technically not necessary in C++ but still good style
}

Send message to specific client with socket.io and node.js

Socket.IO allows you to “namespace” your sockets, which essentially means assigning different endpoints or paths.

This might help: http://socket.io/docs/rooms-and-namespaces/

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

If you are using Brunch, you can add this at the end of your brunch-config.js:

npm: {
    enabled: true,
    globals: {
        $: 'jquery', jQuery: 'jquery', 'Tether': 'tether'
    }
}

Bootstrap 3 grid with no gap

Simple you can use bellow class.

_x000D_
_x000D_
.nopadmar {_x000D_
   padding: 0 !important;_x000D_
   margin: 0 !important;_x000D_
}
_x000D_
<div class="container-fluid">_x000D_
  <div class="row">_x000D_
    <div class="col-md-6 nopadmar">Your Content<div>_x000D_
       <div class="col-md-6 nopadmar">Your Content<div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

source of historical stock data

A former project of mine was going to use freely downloadable data from EODData.

How to extract this specific substring in SQL Server?

select substring(your_field, CHARINDEX(';',your_field)+1 ,CHARINDEX('[',your_field)-CHARINDEX(';',your_field)-1) from your_table

Can't get the others to work. I believe you just want what is in between ';' and '[' in all cases regardless of how long the string in between is. After specifying the field in the substring function, the second argument is the starting location of what you will extract. That is, where the ';' is + 1 (fourth position - the c), because you don't want to include ';'. The next argument takes the location of the '[' (position 14) and subtracts the location of the spot after the ';' (fourth position - this is why I now subtract 1 in the query). This basically says substring(field,location I want substring to begin, how long I want substring to be). I've used this same function in other cases. If some of the fields don't have ';' and '[', you'll want to filter those out in the "where" clause, but that's a little different than the question. If your ';' was say... ';;;', you would use 3 instead of 1 in the example. Hope this helps!

How to get an isoformat datetime string including the default timezone?

You need to make your datetime objects timezone aware. from the datetime docs:

There are two kinds of date and time objects: “naive” and “aware”. This distinction refers to whether the object has any notion of time zone, daylight saving time, or other kind of algorithmic or political time adjustment. Whether a naive datetime object represents Coordinated Universal Time (UTC), local time, or time in some other timezone is purely up to the program, just like it’s up to the program whether a particular number represents metres, miles, or mass. Naive datetime objects are easy to understand and to work with, at the cost of ignoring some aspects of reality.

When you have an aware datetime object, you can use isoformat() and get the output you need.

To make your datetime objects aware, you'll need to subclass tzinfo, like the second example in here, or simpler - use a package that does it for you, like pytz or python-dateutil

Using pytz, this would look like:

import datetime, pytz
datetime.datetime.now(pytz.timezone('US/Central')).isoformat()

You can also control the output format, if you use strftime with the '%z' format directive like

datetime.datetime.now(pytz.timezone('US/Central')).strftime('%Y-%m-%dT%H:%M:%S.%f%z')

How to start an Intent by passing some parameters to it?

In order to pass the parameters you create new intent and put a parameter map:

Intent myIntent = new Intent(this, NewActivityClassName.class);
myIntent.putExtra("firstKeyName","FirstKeyValue");
myIntent.putExtra("secondKeyName","SecondKeyValue");
startActivity(myIntent);

In order to get the parameters values inside the started activity, you must call the get[type]Extra() on the same intent:

// getIntent() is a method from the started activity
Intent myIntent = getIntent(); // gets the previously created intent
String firstKeyName = myIntent.getStringExtra("firstKeyName"); // will return "FirstKeyValue"
String secondKeyName= myIntent.getStringExtra("secondKeyName"); // will return "SecondKeyValue"

If your parameters are ints you would use getIntExtra() instead etc. Now you can use your parameters like you normally would.

How to pass event as argument to an inline event handler in JavaScript?

You don't need to pass this, there already is the event object passed by default automatically, which contains event.target which has the object it's coming from. You can lighten your syntax:

This:

<p onclick="doSomething()">

Will work with this:

function doSomething(){
  console.log(event);
  console.log(event.target);
}

You don't need to instantiate the event object, it's already there. Try it out. And event.target will contain the entire object calling it, which you were referencing as "this" before.

Now if you dynamically trigger doSomething() from somewhere in your code, you will notice that event is undefined. This is because it wasn't triggered from an event of clicking. So if you still want to artificially trigger the event, simply use dispatchEvent:

document.getElementById('element').dispatchEvent(new CustomEvent("click", {'bubbles': true}));

Then doSomething() will see event and event.target as per usual!

No need to pass this everywhere, and you can keep your function signatures free from wiring information and simplify things.

Get GMT Time in Java

Odds are good you did the right stuff on the back end in getting the date, but there's nothing to indicate that you didn't take that GMT time and format it according to your machine's current locale.

final Date currentTime = new Date();

final SimpleDateFormat sdf =
        new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z");

// Give it to me in GMT time.
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("GMT time: " + sdf.format(currentTime));

The key is to use your own DateFormat, not the system provided one. That way you can set the DateFormat's timezone to what you wish, instead of it being set to the Locale's timezone.

Print text instead of value from C enum

I know I am late to the party, but how about this?

const char* dayNames[] = { [Sunday] = "Sunday", [Monday] = "Monday", /*and so on*/ };
printf("%s", dayNames[Sunday]); // prints "Sunday"

This way, you do not have to manually keep the enum and the char* array in sync. If you are like me, chances are that you will later change the enum, and the char* array will print invalid strings. This may not be a feature universally supported. But afaik, most of the mordern day C compilers support this designated initialier style.

You can read more about designated initializers here.

'pip install' fails for every package ("Could not find a version that satisfies the requirement")

Support for TLS 1.0 and 1.1 was dropped for PyPI. If your system does not use a more recent version, it could explain your error.

Could you try reinstalling pip system-wide, to update your system dependencies to a newer version of TLS?

This seems to be related to Unable to install Python libraries

See Dominique Barton's answer:

Apparently pip is trying to access PyPI via HTTPS (which is encrypted and fine), but with an old (insecure) SSL version. Your system seems to be out of date. It might help if you update your packages.

On Debian-based systems I'd try:

apt-get update && apt-get upgrade python-pip

On Red Hat Linux-based systems:

yum update python-pip # (or python2-pip, at least on Red Hat Linux 7)

On Mac:

sudo easy_install -U pip

You can also try to update openssl separately.

View/edit ID3 data for MP3 files

TagLib Sharp has support for reading ID3 tags.

Handling a Menu Item Click Event - Android

Add Following Code

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.new_item:
        Intent i = new Intent(this,SecondActivity.class);
            this.startActivity(i);
            return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

How to upload & Save Files with Desired name

 <html>
<head>
<title>PHP Reanme image example</title>
</head>
<body>

<form action="fileupload.php" enctype="multipart/form-data" method="post">
Select image :
<input type="file" name="file"><br/>
Enter image name :<input type="text" name="filename"><br/>
<input type="submit" value="Upload" name="Submit1">

</form>

<?php

if(isset($_POST['Submit1']))
{ 


$extension = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
$name = $_POST["filename"];

move_uploaded_file($_FILES["file"]["tmp_name"], $name.".".$extension);
echo "Old Image Name = ". $_FILES["file"]["name"]."<br/>";
echo "New Image Name = " . $name.".".$extension;

}


?>
</body>
</html>

Click [here] (https://meeraacademy.com/php-rename-image-while-image-uploading/

Why does my Eclipse keep not responding?

Very likely your filesystem is out of sync with your Eclipse... Resource is out of sync with the file system. Using SVN? If you "Refresh" all of your projects in explorer, speed returns to normal.

How do you load custom UITableViewCells from Xib files?

Register

After iOS 7, this process has been simplified down to (swift 3.0):

// For registering nib files
tableView.register(UINib(nibName: "MyCell", bundle: Bundle.main), forCellReuseIdentifier: "cell")

// For registering classes
tableView.register(MyCellClass.self, forCellReuseIdentifier: "cell")

(Note) This is also achievable by creating the cells in the .xib or .stroyboard files, as prototype cells. If you need to attach a class to them, you can select the cell prototype and add the corresponding class (must be a descendant of UITableViewCell, of course).

Dequeue

And later on, dequeued using (swift 3.0):

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell : UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    cell.textLabel?.text = "Hello"

    return cell
}

The difference being that this new method not only dequeues the cell, it also creates if non-existant (that means that you don't have to do if (cell == nil) shenanigans), and the cell is ready to use just as in the example above.

(Warning) tableView.dequeueReusableCell(withIdentifier:for:) has the new behavior, if you call the other one (without indexPath:) you get the old behavior, in which you need to check for nil and instance it yourself, notice the UITableViewCell? return value.

if let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? MyCellClass
{
    // Cell be casted properly
    cell.myCustomProperty = true
}
else
{
    // Wrong type? Wrong identifier?
}

And of course, the type of the associated class of the cell is the one you defined in the .xib file for the UITableViewCell subclass, or alternatively, using the other register method.

Configuration

Ideally, your cells have been already configured in terms of appearance and content positioning (like labels and image views) by the time you registered them, and on the cellForRowAtIndexPath method you simply fill them in.

All together

class MyCell : UITableViewCell
{
    // Can be either created manually, or loaded from a nib with prototypes
    @IBOutlet weak var labelSomething : UILabel? = nil
}

class MasterViewController: UITableViewController 
{
    var data = ["Hello", "World", "Kinda", "Cliche", "Though"]

    // Register
    override func viewDidLoad()
    {
        super.viewDidLoad()

        tableView.register(MyCell.self, forCellReuseIdentifier: "mycell")
        // or the nib alternative
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return data.count
    }

    // Dequeue
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "mycell", for: indexPath) as! MyCell

        cell.labelSomething?.text = data[indexPath.row]

        return cell
    }
}

And of course, this is all available in ObjC with the same names.

How do I change the default port (9000) that Play uses when I execute the "run" command?

On Windows maybe the play "run 9001" will not work. You have to change the play.bat file. See Ticket

Android emulator failed to allocate memory 8

I had the same problem and what ended up being the issue was the RAM size: apparently 1024 (or whatever size) is different from 1024MB. Make sure you specify the units and it should work for you.

Serializing and submitting a form with jQuery and PHP

Have you checked in console if data from form is properly serialized? Is ajax request successful? Also you didn't close placeholder quote in, which can cause some problems:

 <textarea name="comentarii" cols="36" rows="5" placeholder="Message>  

Type.GetType("namespace.a.b.ClassName") returns null

Dictionary<string, Type> typeCache;
...
public static bool TryFindType(string typeName, out Type t) {
    lock (typeCache) {
        if (!typeCache.TryGetValue(typeName, out t)) {
            foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) {
                t = a.GetType(typeName);
                if (t != null)
                    break;
            }
            typeCache[typeName] = t; // perhaps null
        }
    }
    return t != null;
}

Excel VBA Automation Error: The object invoked has disconnected from its clients

You must have used the object, released it ("disconnect"), and used it again. Release object only after you're finished with it, or when calling Form_Closing.

get url content PHP

Use cURL,

Check if you have it via phpinfo();

And for the code:

function getHtml($url, $post = null) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    if(!empty($post)) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    } 
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

C++ Singleton design pattern

You could avoid memory allocation. There are many variants, all having problems in case of multithreading environment.

I prefer this kind of implementation (actually, it is not correctly said I prefer, because I avoid singletons as much as possible):

class Singleton
{
private:
   Singleton();

public:
   static Singleton& instance()
   {
      static Singleton INSTANCE;
      return INSTANCE;
   }
};

It has no dynamic memory allocation.

HttpContext.Current.User.Identity.Name is Empty

Also, especially if you are a developer, make sure that you are in fact connecting to the IIS server and not to the IIS Express that comes with Visual Studio. If you are debugging a project, it's just as easy if not easier sometimes to think you are connected to IIS when you in fact aren't.

Even if you've enabled Windows Authentication and disabled Anonymous Authentication on IIS, this won't make any difference to your Visual Studio simulation.

How do I correct this Illegal String Offset?

I get the same error in WP when I use php ver 7.1.6 - just take your php version back to 7.0.20 and the error will disappear.

QUERY syntax using cell reference

I found out that single quote > double quote > wrapped in ampersands did work. So, for me it looks like this:

=QUERY('Youth Conference Registration'!C:Y,"select C where Y = '"&A1&"'", 0)

How to add new column to an dataframe (to the front not end)?

Use cbind e.g.

df <- data.frame(b = runif(6), c = rnorm(6))
cbind(a = 0, df)

giving:

> cbind(a = 0, df)
  a         b          c
1 0 0.5437436 -0.1374967
2 0 0.5634469 -1.0777253
3 0 0.9018029 -0.8749269
4 0 0.1649184 -0.4720979
5 0 0.6992595  0.6219001
6 0 0.6907937 -1.7416569

Export table data from one SQL Server to another

It can be done through "Import/Export Data..." in SQL Server Management Studio

Things possible in IntelliJ that aren't possible in Eclipse?

Don't forget "compare with clipboard".

Something that I use all the time in IntelliJ and which has no equivalent in Eclipse.

UIButton: how to center an image and a text using imageEdgeInsets and titleEdgeInsets?

Found how.

First, configure the text of titleLabel (because of styles, i.e, bold, italic, etc). Then, use setTitleEdgeInsets considering the width of your image:

[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button setTitle:title forState:UIControlStateNormal];
[button.titleLabel setFont:[UIFont boldSystemFontOfSize:10.0]];

// Left inset is the negative of image width.
[button setTitleEdgeInsets:UIEdgeInsetsMake(0.0, -image.size.width, -25.0, 0.0)]; 

After that, use setTitleEdgeInsets considering the width of text bounds:

[button setImage:image forState:UIControlStateNormal];

// Right inset is the negative of text bounds width.
[button setImageEdgeInsets:UIEdgeInsetsMake(-15.0, 0.0, 0.0, -button.titleLabel.bounds.size.width)];

Now the image and the text will be centered (in this example, the image appears above the text).

Cheers.

JSON Java 8 LocalDateTime format in Spring Boot

@JsonDeserialize(using= LocalDateDeserializer.class) does not work for me with the below dependency.

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version> 2.9.6</version>
</dependency>

I have used the below code converter to deserialize the date into a java.sql.Date.

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;


@SuppressWarnings("UnusedDeclaration")
@Converter(autoApply = true)
public class LocalDateConverter implements AttributeConverter<java.time.LocalDate, java.sql.Date> {


    @Override
    public java.sql.Date convertToDatabaseColumn(java.time.LocalDate attribute) {

        return attribute == null ? null : java.sql.Date.valueOf(attribute);
    }

    @Override
    public java.time.LocalDate convertToEntityAttribute(java.sql.Date dbData) {

        return dbData == null ? null : dbData.toLocalDate();
    }
}

How can I know when an EditText loses focus?

Have your Activity implement OnFocusChangeListener() if you want a factorized use of this interface, example:

public class Shops extends AppCompatActivity implements View.OnFocusChangeListener{

In your OnCreate you can add a listener for example:

editTextResearch.setOnFocusChangeListener(this);
editTextMyWords.setOnFocusChangeListener(this);
editTextPhone.setOnFocusChangeListener(this);

then android studio will prompt you to add the method from the interface, accept it... it will be like:

@Override
public void onFocusChange(View v, boolean hasFocus) {
// todo your code here...
}

and as you've got a factorized code, you'll just have to do that:

@Override
public void onFocusChange(View v, boolean hasFocus) {
   if (hasFocus) {
        editTextResearch.setText("");
        editTextMyWords.setText("");
        editTextPhone.setText("");
    }
    if (!hasFocus){
        editTextResearch.setText("BlaBlaBla");
        editTextMyWords.setText(" One Two Tree!");
        editTextPhone.setText("\"your phone here:\"");
    }
}

anything you code in the !hasFocus is for the behavior of the item that loses focus, that should do the trick! But beware that in such state, the change of focus might overwrite the user's entries!

Move SQL Server 2008 database files to a new folder location

You can use Detach/Attach Option in SQL Server Management Studio.

Check this: Move a Database Using Detach and Attach

Fastest way to get the first n elements of a List into an Array

Option 1 Faster Than Option 2

Because Option 2 creates a new List reference, and then creates an n element array from the List (option 1 perfectly sizes the output array). However, first you need to fix the off by one bug. Use < (not <=). Like,

String[] out = new String[n];
for(int i = 0; i < n; i++) {
    out[i] = in.get(i);
}

R color scatter plot points based on values

Here is a method using a lookup table of thresholds and associated colours to map the colours to the variable of interest.

 # make a grid 'Grd' of points and number points for side of square 'GrdD'
Grd <- expand.grid(seq(0.5,400.5,10),seq(0.5,400.5,10))
GrdD <- length(unique(Grd$Var1))

# Add z-values to the grid points
Grd$z <- rnorm(length(Grd$Var1), mean = 10, sd =2)

# Make a vector of thresholds 'Brks' to colour code z 
Brks <- c(seq(0,18,3),Inf)

# Make a vector of labels 'Lbls' for the colour threhsolds
Lbls <- Lbls <- c('0-3','3-6','6-9','9-12','12-15','15-18','>18')

# Make a vector of colours 'Clrs' for to match each range
Clrs <- c("grey50","dodgerblue","forestgreen","orange","red","purple","magenta")

# Make up lookup dataframe 'LkUp' of the lables and colours 
LkUp <- data.frame(cbind(Lbls,Clrs),stringsAsFactors = FALSE)

# Add a new variable 'Lbls' the grid dataframe mapping the labels based on z-value
Grd$Lbls <- as.character(cut(Grd$z, breaks = Brks, labels = Lbls))

# Add a new variable 'Clrs' to the grid dataframe based on the Lbls field in the grid and lookup table
Grd <- merge(Grd,LkUp, by.x = 'Lbls')

# Plot the grid using the 'Clrs' field for the colour of each point
plot(Grd$Var1,
     Grd$Var2,
     xlim = c(0,400),
     ylim = c(0,400),
     cex = 1.0,
     col = Grd$Clrs,
     pch = 20,
     xlab = 'mX',
     ylab = 'mY',
     main = 'My Grid',
     axes = FALSE,
     labels = FALSE,
     las = 1
)

axis(1,seq(0,400,100))
axis(2,seq(0,400,100),las = 1)
box(col = 'black')

legend("topleft", legend = Lbls, fill = Clrs, title = 'Z')

MySQL how to join tables on two fields

JOIN t2 ON (t2.id = t1.id AND t2.date = t1.date)

How to display loading message when an iFrame is loading?

I have done the following css approach:

<div class="holds-the-iframe"><iframe here></iframe></div>

.holds-the-iframe {
  background:url(../images/loader.gif) center center no-repeat;
}

Overlapping Views in Android

Android handles transparency across views and drawables (including PNG images) natively, so the scenario you describe (a partially transparent ImageView in front of a Gallery) is certainly possible.

If you're having problems it may be related to either the layout or your image. I've replicated the layout you describe and successfully achieved the effect you're after. Here's the exact layout I used.

<RelativeLayout 
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/gallerylayout"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <Gallery
    android:id="@+id/overview"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
  />
  <ImageView
    android:id="@+id/navigmaske"
    android:background="#0000"      
    android:src="@drawable/navigmask"
    android:scaleType="fitXY"
    android:layout_alignTop="@id/overview"
    android:layout_alignBottom="@id/overview"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
  />
</RelativeLayout>

Note that I've changed the parent RelativeLayout to a height and width of fill_parent as is generally what you want for a main Activity. Then I've aligned the top and bottom of the ImageView to the top and bottom of the Gallery to ensure it's centered in front of it.

I've also explicitly set the background of the ImageView to be transparent.

As for the image drawable itself, if you put the PNG file somewhere for me to look at I can use it in my project and see if it's responsible.

Is it valid to have a html form inside another html form?

A non-JavaScript workaround for nesting form tags:

Because you allow for

all fields minus those within "b".

when submitting "a", the following would work, using regular web-forms without fancy JavaScript tricks:

Step 1. Put each form on its own web page.

Step 2. Insert an iframe wherever you want this sub-form to appear.

Step 3. Profit.

I tried to use a code-playground website to show a demo, but many of them prohibit embedding their websites in iframes, even within their own domain.

Merge (with squash) all changes from another branch as a single commit

I have created my own git alias to do exactly this. I'm calling it git freebase! It will take your existing messy, unrebasable feature branch and recreate it so that it becomes a new branch with the same name with its commits squashed into one commit and rebased onto the branch you specify (master by default). At the very end, it will allow you to use whatever commit message you like for your newly "freebased" branch.

Install it by placing the following alias in your .gitconfig:

[alias]
  freebase = "!f() { \
    TOPIC="$(git branch | grep '\\*' | cut -d ' ' -f2)"; \
    NEWBASE="${1:-master}"; \
    PREVSHA1="$(git rev-parse HEAD)"; \
    echo "Freebaseing $TOPIC onto $NEWBASE, previous sha1 was $PREVSHA1"; \
    echo "---"; \
    git reset --hard "$NEWBASE"; \
    git merge --squash "$PREVSHA1"; \
    git commit; \
  }; f"

Use it from your feature branch by running: git freebase <new-base>

I've only tested this a few times, so read it first and make sure you want to run it. As a little safety measure it does print the starting sha1 so you should be able to restore your old branch if anything goes wrong.

I'll be maintaining it in my dotfiles repo on github: https://github.com/stevecrozz/dotfiles/blob/master/.gitconfig

How to overload __init__ method based on argument type?

Quick and dirty fix

class MyData:
    def __init__(string=None,list=None):
        if string is not None:
            #do stuff
        elif list is not None:
            #do other stuff
        else:
            #make data empty

Then you can call it with

MyData(astring)
MyData(None, alist)
MyData()

Deleting Elements in an Array if Element is a Certain value VBA

Sub DelEle(Ary, SameTypeTemp, Index As Integer) '<<<<<<<<< pass only not fixed sized array (i don't know how to declare same type temp array in proceder)
    Dim I As Integer, II As Integer
    II = -1
    If Index < LBound(Ary) And Index > UBound(Ary) Then MsgBox "Error.........."
    For I = 0 To UBound(Ary)
        If I <> Index Then
            II = II + 1
            ReDim Preserve SameTypeTemp(II)
            SameTypeTemp(II) = Ary(I)
        End If
    Next I
    ReDim Ary(UBound(SameTypeTemp))
    Ary = SameTypeTemp
    Erase SameTypeTemp
End Sub

Sub Test()
    Dim a() As Integer, b() As Integer
    ReDim a(3)
    Debug.Print "InputData:"
    For I = 0 To UBound(a)
        a(I) = I
        Debug.Print "    " & a(I)
    Next
    DelEle a, b, 1
    Debug.Print "Result:"
    For I = 0 To UBound(a)
        Debug.Print "    " & a(I)
    Next
End Sub

Why are C# 4 optional parameters defined on interface not enforced on implementing class?

An optional parameter is just tagged with an attribute. This attribute tells the compiler to insert the default value for that parameter at the call-site.

The call obj2.TestMethod(); is replaced by obj2.TestMethod(false); when the C# code gets compiled to IL, and not at JIT-time.

So in a way it's always the caller providing the default value with optional parameters. This also has consequences on binary versioning: If you change the default value but don't recompile the calling code it will continue to use the old default value.

On the other hand, this disconnect means you can't always use the concrete class and the interface interchangeably.

You already can't do that if the interface method was implemented explicitly.

Authenticating in PHP using LDAP through Active Directory

You would think that simply authenticating a user in Active Directory would be a pretty simple process using LDAP in PHP without the need for a library. But there are a lot of things that can complicate it pretty fast:

  • You must validate input. An empty username/password would pass otherwise.
  • You should ensure the username/password is properly encoded when binding.
  • You should be encrypting the connection using TLS.
  • Using separate LDAP servers for redundancy in case one is down.
  • Getting an informative error message if authentication fails.

It's actually easier in most cases to use a LDAP library supporting the above. I ultimately ended up rolling my own library which handles all the above points: LdapTools (Well, not just for authentication, it can do much more). It can be used like the following:

use LdapTools\Configuration;
use LdapTools\DomainConfiguration;
use LdapTools\LdapManager;

$domain = (new DomainConfiguration('example.com'))
    ->setUsername('username') # A separate AD service account used by your app
    ->setPassword('password')
    ->setServers(['dc1', 'dc2', 'dc3'])
    ->setUseTls(true);
$config = new Configuration($domain);
$ldap = new LdapManager($config);

if (!$ldap->authenticate($username, $password, $message)) {
    echo "Error: $message";
} else {
    // Do something...
}

The authenticate call above will:

  • Validate that neither the username or password is empty.
  • Ensure the username/password is properly encoded (UTF-8 by default)
  • Try an alternate LDAP server in case one is down.
  • Encrypt the authentication request using TLS.
  • Provide additional information if it failed (ie. locked/disabled account, etc)

There are other libraries to do this too (Such as Adldap2). However, I felt compelled enough to provide some additional information as the most up-voted answer is actually a security risk to rely on with no input validation done and not using TLS.

Error You must specify a region when running command aws ecs list-container-instances

I think you need to use for example:

aws ecs list-container-instances --cluster default --region us-east-1

This depends of your region of course.

Convert R vector to string vector of 1 element

Use the collapse argument to paste:

paste(a,collapse=" ")
[1] "aa bb cc"

Best way to copy a database (SQL Server 2008)

The detach/copy/attach method will take down the database. That's not something you'd want in production.

The backup/restore will only work if you have write permissions to the production server. I work with Amazon RDS and I don't.

The import/export method doesn't really work because of foreign keys - unless you do tables one by one in the order they reference one another. You can do an import/export to a new database. That will copy all the tables and data, but not the foreign keys.

This sounds like a common operation one needs to do with database. Why isn't SQL Server handling this properly? Every time I had to do this it was frustrating.

That being said, the only painless solution I've encountered was Sql Azure Migration Tool which is maintained by the community. It works with SQL Server too.

Init method in Spring Controller (annotation version)

public class InitHelloWorld implements BeanPostProcessor {

   public Object postProcessBeforeInitialization(Object bean,
             String beanName) throws BeansException {
       System.out.println("BeforeInitialization : " + beanName);
       return bean;  // you can return any other object as well
   }

   public Object postProcessAfterInitialization(Object bean,
             String beanName) throws BeansException {
       System.out.println("AfterInitialization : " + beanName);
       return bean;  // you can return any other object as well
   }

}

Display PDF file inside my android application

I do not think that you can do this easily. you should consider this answer here:

How can I display a pdf document into a Webview?

basically you'll be able to see a pdf if it is hosted online via google documents, but not if you have it in your device (you'll need a standalone reader for that)

What does the PHP error message "Notice: Use of undefined constant" mean?

You should quote your array keys:

$department = mysql_real_escape_string($_POST['department']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$message = mysql_real_escape_string($_POST['message']);

As is, it was looking for constants called department, name, email, message, etc. When it doesn't find such a constant, PHP (bizarrely) interprets it as a string ('department', etc). Obviously, this can easily break if you do defined such a constant later (though it's bad style to have lower-case constants).

Convert CString to const char*

Note: This answer predates the Unicode requirement; see the comments.

Just cast it:

CString s;
const TCHAR* x = (LPCTSTR) s;

It works because CString has a cast operator to do exactly this.

Using TCHAR makes your code Unicode-independent; if you're not concerned about Unicode you can simply use char instead of TCHAR.

Remove Unnamed columns in pandas dataframe

The approved solution doesn't work in my case, so my solution is the following one:

    ''' The column name in the example case is "Unnamed: 7"
 but it works with any other name ("Unnamed: 0" for example). '''

        df.rename({"Unnamed: 7":"a"}, axis="columns", inplace=True)

        # Then, drop the column as usual.

        df.drop(["a"], axis=1, inplace=True)

Hope it helps others.

Convert dd-mm-yyyy string to date

_x000D_
_x000D_
let dateString  = '13-02-2021' //date string in dd-mm-yyyy format

let dateArray = dateString.split("-");
//dateArray[2] equals to 2021
//dateArray[1] equals to 02
//dateArray[0] equals to 13

// using template literals below

let dateObj = new Date(`${dateArray[2]}-${dateArray[1]}-${dateArray[0]}`);

// dateObj equals to Sat Feb 13 2021 05:30:00 GMT+0530 (India Standard Time)

//I'm from India so its showing GMT+0530
_x000D_
_x000D_
_x000D_

P.S : Always refer docs for basics, MDN or DevDocs

How can I get a specific field of a csv file?

import csv
mycsv = csv.reader(open(myfilepath))
for row in mycsv:
   text = row[1]

Following the comments to the SO question here, a best, more robust code would be:

import csv
with open(myfilepath, 'rb') as f:
    mycsv = csv.reader(f)
    for row in mycsv:
        text = row[1]
        ............

Update: If what the OP actually wants is the last string in the last row of the csv file, there are several aproaches that not necesarily needs csv. For example,

fulltxt = open(mifilepath, 'rb').read()
laststring = fulltxt.split(',')[-1]

This is not good for very big files because you load the complete text in memory but could be ok for small files. Note that laststring could include a newline character so strip it before use.

And finally if what the OP wants is the second string in line n (for n=2):

Update 2: This is now the same code than the one in the answer from J.F.Sebastian. (The credit is for him):

import csv
line_number = 2     
with open(myfilepath, 'rb') as f:
    mycsv = csv.reader(f)
    mycsv = list(mycsv)
    text = mycsv[line_number][1]
    ............

python NameError: global name '__file__' is not defined

This error comes when you append this line os.path.join(os.path.dirname(__file__)) in python interactive shell.

Python Shell doesn't detect current file path in __file__ and it's related to your filepath in which you added this line

So you should write this line os.path.join(os.path.dirname(__file__)) in file.py. and then run python file.py, It works because it takes your filepath.

CSS display:inline property with list-style-image: property on <li> tags

Try using float: left (or right) instead of display: inline. Inline display replaces list-item display, which is what adds the bullet points.

How to run SQL script in MySQL?

You have quite a lot of options:

  • use the MySQL command line client: mysql -h hostname -u user database < path/to/test.sql
  • Install the MySQL GUI tools and open your SQL file, then execute it
  • Use phpmysql if the database is available via your webserver

document.getElementById vs jQuery $()

Close, but not the same. They're getting the same element, but the jQuery version is wrapped in a jQuery object.

The equivalent would be this

var contents = $('#contents').get(0);

or this

var contents = $('#contents')[0];

These will pull the element out of the jQuery object.

How do I configure IIS for URL Rewriting an AngularJS application in HTML5 mode?

I've been trying to deploy a simple Angular 7 application, to an Azure Web App. Everything worked fine, until the point where you refreshed the page. Doing so, was presenting me with an 500 error - moved content. I've read both on the Angular docs and in around a good few forums, that I need to add a web.config file to my deployed solution and make sure the rewrite rule fallback to the index.html file. After hours of frustration and trial and error tests, I've found the error was quite simple: adding a tag around my file markup.

How do I get whole and fractional parts from double in JSP/Java?

[Edit: The question originally asked how to get the mantissa and exponent.]

Where n is the number to get the real mantissa/exponent:

exponent = int(log(n))
mantissa = n / 10^exponent

Or, to get the answer you were looking for:

exponent = int(n)
mantissa = n - exponent

These are not Java exactly but should be easy to convert.

How to fix: "No suitable driver found for jdbc:mysql://localhost/dbname" error when using pools?

add the artifact from maven.

 <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
 </dependency>

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

None of the other solution worked for me.

Even if I don't think its the best practice, I Had to add it into the code like this

configuration.addAnnotatedClass(com.myOrg.entities.Person.class);

here

public static SessionFactory getSessionFactory() {
    Configuration configuration = new Configuration().configure();

    configuration.addAnnotatedClass(com.myOrg.entities.Person.class);

    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties());
    SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
    return sessionFactory;
}

How to execute powershell commands from a batch file?

This solution is similar to walid2mi (thank you for inspiration), but allows the standard console input by the Read-Host cmdlet.

pros:

  • can be run like standard .cmd file
  • only one file for batch and powershell script
  • powershell script may be multi-line (easy to read script)
  • allows the standard console input (use the Read-Host cmdlet by standard way)

cons:

  • requires powershell version 2.0+

Commented and runable example of batch-ps-script.cmd:

<# : Begin batch (batch script is in commentary of powershell v2.0+)
@echo off
: Use local variables
setlocal
: Change current directory to script location - useful for including .ps1 files
cd %~dp0
: Invoke this file as powershell expression
powershell -executionpolicy remotesigned -Command "Invoke-Expression $([System.IO.File]::ReadAllText('%~f0'))"
: Restore environment variables present before setlocal and restore current directory
endlocal
: End batch - go to end of file
goto:eof
#>
# here start your powershell script

# example: include another .ps1 scripts (commented, for quick copy-paste and test run)
#. ".\anotherScript.ps1"

# example: standard input from console
$variableInput = Read-Host "Continue? [Y/N]"
if ($variableInput -ne "Y") {
    Write-Host "Exit script..."
    break
}

# example: call standard powershell command
Get-Item .

Snippet for .cmd file:

<# : batch script
@echo off
setlocal
cd %~dp0
powershell -executionpolicy remotesigned -Command "Invoke-Expression $([System.IO.File]::ReadAllText('%~f0'))"
endlocal
goto:eof
#>
# here write your powershell commands...

Variables declared outside function

When Python parses a function, it notes when a variable assignment is made. When there is an assignment, it assumes by default that that variable is a local variable. To declare that the assignment refers to a global variable, you must use the global declaration.

When you access a variable in a function, its value is looked up using the LEGB scoping rules.


So, the first example

  x = 1
  def inc():
      x += 5
  inc()

produces an UnboundLocalError because Python determined x inside inc to be a local variable,

while accessing x works in your second example

 def inc():
    print x

because here, in accordance with the LEGB rule, Python looks for x in the local scope, does not find it, then looks for it in the extended scope, still does not find it, and finally looks for it in the global scope successfully.

Java ArrayList how to add elements at the beginning

You can use list methods, remove and add

list.add(lowestIndex, element);
list.remove(highestIndex, element);

ASP.NET MVC Dropdown List From SelectList

Try this, just an example:

u.UserTypeOptions = new SelectList(new[]
    {
        new { ID="1", Name="name1" },
        new { ID="2", Name="name2" },
        new { ID="3", Name="name3" },
    }, "ID", "Name", 1);

Or

u.UserTypeOptions = new SelectList(new List<SelectListItem>
    {
        new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
        new SelectListItem { Selected = false, Text = "Homeowner", Value = "2"},
        new SelectListItem { Selected = false, Text = "Contractor", Value = "3"},
    },"Value","Text");

PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

8388608 bytes is 8M, the default limit in PHP. Update your post_max_size in php.ini to a larger value.

upload_max_filesize sets the max file size that a user can upload while post_max_size sets the maximum amount of data that can be sent via a POST in a form.

So you can set upload_max_filesize to 1 meg, which will mean that the biggest single file a user can upload is 1 megabyte, but they could upload 5 of them at once if the post_max_size was set to 5.

Difference between java.exe and javaw.exe

java.exe is the console app while javaw.exe is windows app (console-less). You can't have Console with javaw.exe.

Onclick on bootstrap button

<a class="btn btn-large btn-success" id="fire" href="http://twitter.github.io/bootstrap/examples/marketing-narrow.html#">Send Email</a>

$('#fire').on('click', function (e) {

     //your awesome code here

})

How to use a WSDL

In visual studio.

  • Create or open a project.
  • Right-click project from solution explorer.
  • Select "Add service refernce"
  • Paste the address with WSDL you received.
  • Click OK.

If no errors, you should be able to see the service reference in the object browser and all related methods.

Python List & for-each access (Find/Replace in built-in list)

Python is not Java, nor C/C++ -- you need to stop thinking that way to really utilize the power of Python.

Python does not have pass-by-value, nor pass-by-reference, but instead uses pass-by-name (or pass-by-object) -- in other words, nearly everything is bound to a name that you can then use (the two obvious exceptions being tuple- and list-indexing).

When you do spam = "green", you have bound the name spam to the string object "green"; if you then do eggs = spam you have not copied anything, you have not made reference pointers; you have simply bound another name, eggs, to the same object ("green" in this case). If you then bind spam to something else (spam = 3.14159) eggs will still be bound to "green".

When a for-loop executes, it takes the name you give it, and binds it in turn to each object in the iterable while running the loop; when you call a function, it takes the names in the function header and binds them to the arguments passed; reassigning a name is actually rebinding a name (it can take a while to absorb this -- it did for me, anyway).

With for-loops utilizing lists, there are two basic ways to assign back to the list:

for i, item in enumerate(some_list):
    some_list[i] = process(item)

or

new_list = []
for item in some_list:
    new_list.append(process(item))
some_list[:] = new_list

Notice the [:] on that last some_list -- it is causing a mutation of some_list's elements (setting the entire thing to new_list's elements) instead of rebinding the name some_list to new_list. Is this important? It depends! If you have other names besides some_list bound to the same list object, and you want them to see the updates, then you need to use the slicing method; if you don't, or if you do not want them to see the updates, then rebind -- some_list = new_list.

Better/Faster to Loop through set or list?

While a set may be what you want structure-wise, the question is what is faster. A list is faster. Your example code doesn't accurately compare set vs list because you're converting from a list to a set in set_loop, and then you're creating the list you'll be looping through in list_loop. The set and list you iterate through should be constructed and in memory ahead of time, and simply looped through to see which data structure is faster at iterating:

ids_list = range(1000000)
ids_set = set(ids)
def f(x):
    for i in x:
         pass

%timeit f(ids_set)
#1 loops, best of 3: 214 ms per loop
%timeit f(ids_list)
#1 loops, best of 3: 176 ms per loop

Remove empty lines in a text file via grep

If removing empty lines means lines including any spaces, use:

grep '\S' FILE

For example:

$  printf "line1\n\nline2\n \nline3\n\t\nline4\n" > FILE
$  cat -v FILE
line1

line2

line3

line4
$  grep '\S' FILE
line1
line2
line3
line4
$  grep . FILE
line1
line2

line3

line4

See also:

composer laravel create project

First, you have to locate the project directory in cmd After this fire below command and 'first_laravel_app' is the project name you can replace it with your own project name.

composer create-project laravel/laravel first_laravel_app --prefer-dist

How to change font size in Eclipse for Java text editors?

On Mac:

  1. Eclipse toolbar Eclipse ? Preferences OR Command + , (comma)

  2. General ? Appearance ? Colors and Fonts ? Basic ? Text Font

  3. Apply

How do I set log4j level on the command line?

Based on @lijat, here is a simplified implementation. In my spring-based application I simply load this as a bean.

public static void configureLog4jFromSystemProperties()
{
  final String LOGGER_PREFIX = "log4j.logger.";

  for(String propertyName : System.getProperties().stringPropertyNames())
  {
    if (propertyName.startsWith(LOGGER_PREFIX)) {
      String loggerName = propertyName.substring(LOGGER_PREFIX.length());
      String levelName = System.getProperty(propertyName, "");
      Level level = Level.toLevel(levelName); // defaults to DEBUG
      if (!"".equals(levelName) && !levelName.toUpperCase().equals(level.toString())) {
        logger.error("Skipping unrecognized log4j log level " + levelName + ": -D" + propertyName + "=" + levelName);
        continue;
      }
      logger.info("Setting " + loggerName + " => " + level.toString());
      Logger.getLogger(loggerName).setLevel(level);
    }
  }
}

Global variables in Javascript across multiple files

OK, guys, here's my little test too. I had a similar problem, so I decided to test out 3 situations:

  1. One HTML file, one external JS file... does it work at all - can functions communicate via a global var?
  2. Two HTML files, one external JS file, one browser, two tabs: will they interfere via the global var?
  3. One HTML file, open by 2 browsers, will it work and will they interfere?

All the results were as expected.

  1. It works. Functions f1() and f2() communicate via global var (var is in the external JS file, not in HTML file).
  2. They do not interfere. Apparently distinct copies of JS file have been made for each browser tab, each HTML page.
  3. All works independently, as expected.

Instead of browsing tutorials, I found it easier to try it out, so I did. My conclusion: whenever you include an external JS file in your HTML page, the contents of the external JS gets "copy/pasted" into your HTML page before the page is rendered. Or into your PHP page if you will. Please correct me if I'm wrong here. Thanx.

My example files follow:

EXTERNAL JS:

var global = 0;

function f1()
{
    alert('fired: f1');
    global = 1;
    alert('global changed to 1');
}

function f2()
{
    alert('fired f2');
    alert('value of global: '+global);
}

HTML 1:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>

HTML 2

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index2.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>

Color text in terminal applications in UNIX

You probably want ANSI color codes. Most *nix terminals support them.

HashMap: One Key, multiple Values

Write a new class that holds all the values that you need and use the new class's object as the value in your HashMap

HashMap<String, MyObject>

class MyObject {
public String value1;
public int value2;
public List<String> value3;
}

How do I lowercase a string in Python?

Use .lower() - For example:

s = "Kilometer"
print(s.lower())

The official 2.x documentation is here: str.lower()
The official 3.x documentation is here: str.lower()

jQuery How to Get Element's Margin and Padding?

According to the jQuery documentation, shorthand CSS properties are not supported.

Depending on what you mean by "total padding", you may be able to do something like this:

var $img = $('img');
var paddT = $img.css('padding-top') + ' ' + $img.css('padding-right') + ' ' + $img.css('padding-bottom') + ' ' + $img.css('padding-left');

How to change the data type of a column without dropping the column with query?

If ALTER COLUMN doesn't work.

It is not unusual for alter column to fail because it cannot make the transformation you desire. In this case, the solution is to create a dummy table TableName_tmp, copy the data over with your specialized transformation in the bulk Insert command, drop the original table, and rename the tmp table to the original table's name. You'll have to drop and recreate the Foreign key constraints and, for performance, you'll probably want to create keys after filling the tmp table.

Sound like a lot of work? Actually, it isn't.

If you are using SQL Server, you can make the SQL Server Management Studio do the work for you!

  • Bring up your table structure (right-click on the table column and select "Modify")
  • Make all of your changes (if the column transformation is illegal, just add your new column - you'll patch it up in a moment).
  • Right-click on the background of the Modify window and select "Generate Change Script." In the window that appears, you can copy the change script to the clipboard.
  • Cancel the Modify (you'll want to test your script, after all) and then paste the script into a new query window.
  • Modify as necessary (e.g. add your transformation while removing the field from the tmp table declaration) and you now have the script necessary to make your transformation.

Inserting string at position x of another string

Well just a small change 'cause the above solution outputs

"I want anapple"

instead of

"I want an apple"

To get the output as

"I want an apple"

use the following modified code

var output = a.substr(0, position) + " " + b + a.substr(position);

What is the correct way of reading from a TCP socket in C/C++?

For any non-trivial application (I.E. the application must receive and handle different kinds of messages with different lengths), the solution to your particular problem isn't necessarily just a programming solution - it's a convention, I.E. a protocol.

In order to determine how many bytes you should pass to your read call, you should establish a common prefix, or header, that your application receives. That way, when a socket first has reads available, you can make decisions about what to expect.

A binary example might look like this:

#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <arpa/inet.h>

enum MessageType {
    MESSAGE_FOO,
    MESSAGE_BAR,
};

struct MessageHeader {
    uint32_t type;
    uint32_t length;
};

/**
 * Attempts to continue reading a `socket` until `bytes` number
 * of bytes are read. Returns truthy on success, falsy on failure.
 *
 * Similar to @grieve's ReadXBytes.
 */
int readExpected(int socket, void *destination, size_t bytes)
{
    /*
    * Can't increment a void pointer, as incrementing
    * is done by the width of the pointed-to type -
    * and void doesn't have a width
    *
    * You can in GCC but it's not very portable
    */
    char *destinationBytes = destination;
    while (bytes) {
        ssize_t readBytes = read(socket, destinationBytes, bytes);
        if (readBytes < 1)
            return 0;
        destinationBytes += readBytes;
        bytes -= readBytes;
    }
    return 1;
}

int main(int argc, char **argv)
{
    int selectedFd;

    // use `select` or `poll` to wait on sockets
    // received a message on `selectedFd`, start reading

    char *fooMessage;
    struct {
        uint32_t a;
        uint32_t b;
    } barMessage;

    struct MessageHeader received;
    if (!readExpected (selectedFd, &received, sizeof(received))) {
        // handle error
    }
    // handle network/host byte order differences maybe
    received.type = ntohl(received.type);
    received.length = ntohl(received.length);

    switch (received.type) {
        case MESSAGE_FOO:
            // "foo" sends an ASCII string or something
            fooMessage = calloc(received.length + 1, 1);
            if (readExpected (selectedFd, fooMessage, received.length))
                puts(fooMessage);
            free(fooMessage);
            break;
        case MESSAGE_BAR:
            // "bar" sends a message of a fixed size
            if (readExpected (selectedFd, &barMessage, sizeof(barMessage))) {
                barMessage.a = ntohl(barMessage.a);
                barMessage.b = ntohl(barMessage.b);
                printf("a + b = %d\n", barMessage.a + barMessage.b);
            }
            break;
        default:
            puts("Malformed type received");
            // kick the client out probably
    }
}

You can likely already see one disadvantage of using a binary format - for each attribute greater than a char you read, you will have to ensure its byte order is correct using the ntohl or ntohs functions.

An alternative is to use byte-encoded messages, such as simple ASCII or UTF-8 strings, which avoid byte-order issues entirely but require extra effort to parse and validate.

There are two final considerations for network data in C.

The first is that some C types do not have fixed widths. For example, the humble int is defined as the word size of the processor, so 32 bit processors will produce 32 bit ints, while 64 bit processors will produces 64 bit ints. Good, portable code should have network data use fixed-width types, like those defined in stdint.h.

The second is struct padding. A struct with different-widthed members will add data in between some members to maintain memory alignment, making the struct faster to use in the program but sometimes producing confusing results.

#include <stdio.h>
#include <stdint.h>

int main()
{
    struct A {
        char a;
        uint32_t b;
    } A;

    printf("sizeof(A): %ld\n", sizeof(A));
}

In this example, its actual width won't be 1 char + 4 uint32_t = 5 bytes, it'll be 8:

mharrison@mharrison-KATANA:~$ gcc -o padding padding.c
mharrison@mharrison-KATANA:~$ ./padding 
sizeof(A): 8

This is because 3 bytes are added after char a to make sure uint32_t b is memory-aligned.

So if you write a struct A, then attempt to read a char and a uint32_t on the other side, you'll get char a, and a uint32_t where the first three bytes are garbage and the last byte is the first byte of the actual integer you wrote.

Either document your data format explicitly as C struct types or, better yet, document any padding bytes they might contain.

Connect Android to WiFi Enterprise network EAP(PEAP)

Thanks for enlightening us Cypawer.

I also tried this app https://play.google.com/store/apps/details?id=com.oneguyinabasement.leapwifi

and it worked flawlessly.

Leap Wifi Connector

Pytorch tensor to numpy array

There are 4 dimensions of the tensor you want to convert.

[:, ::-1, :, :] 

: means that the first dimension should be copied as it is and converted, same goes for the third and fourth dimension.

::-1 means that for the second axes it reverses the the axes

How to append a date in batch files

I've used the environment variables technique covered here: http://cwashington.netreach.net/depo/view.asp?Index=19

http://cwashington.netreach.net/depo/default.asp?topic=repository&move=last&ScriptType=command&SubType=Misc

Here's the code from that site:

::~~Author~~.          Brett Middleton
::~~Email_Address~~. [email protected]
::~~Script_Type~~.   nt command line batch
::~~Sub_Type~~. Misc
::~~Keywords~~. environment variables

::~~Comment~~.
::Sets or clears a group of environment variables containing components of the current date extracted from the string returned by the DATE /T command.  These variables can be used to name files, control the flow of execution, etc.

::~~Script~~.

@echo off

::-----------------------------------------------------------------------------
::  SetEnvDate1.CMD                                                     6/30/98
::-----------------------------------------------------------------------------
::  Description  :  Sets or clears a group of environment variables containing
::               :  components of the current date extracted from the string
::               :  returned by the DATE /T command.  These variables can be
::               :  used to name files, control the flow of execution, etc.
::               :
::  Requires     :  Windows NT with command extensions enabled
::               :
::  Tested       :  Yes, as demonstration
::               :
::  Contact      :  Brett Middleton <[email protected]>
::               :  Animal and Dairy Science Department
::               :  University of Georgia, Athens
::-----------------------------------------------------------------------------
::  USAGE
::
::  SetEnvDate1 can be used as a model for coding date/time routines in
::  other scripts, or can be used by itself as a utility that is called
::  from other scripts.
::  
::  Run or call SetEnvDate1 without arguments to set the date variables.
::  Variables are set for the day abbreviation (DT_DAY), month number (DT_MM),
::  day number (DT_DD) and four-digit year (DT_YYYY).
::
::  When the variables are no longer needed, clean up the environment by
::  calling the script again with the CLEAR argument.  E.g.,
::
::       call SetEnvDate1 clear
::-----------------------------------------------------------------------------
::  NOTES
::
::  A time variable could be added by parsing the string returned by the
::  built-in TIME /T command.  This is left as an exercise for the reader. B-)
::
::  This script illustrates the following NT command extensions:
::
::  1.  Use of the extended IF command to do case-insensitive comparisons.
::
::  2.  Use of the extended DATE command.
::
::  3.  Use of the extended FOR command to parse a string returned by a
::      command or program.
::
::  4.  Use of the "()" conditional processing symbols to group commands
::      for conditional execution.  All commands between the parens will
::      be executed if the preceeding IF or FOR statement is TRUE.
::-----------------------------------------------------------------------------

if not "%1" == "?" goto chkarg
echo.
echo Sets or clears date/time variables in the command environment.
echo.
echo    SetEnvDate1 [clear]
echo.
echo When called without arguments, the variables are created or updated.
echo When called with the CLEAR argument, the variables are deleted.
echo.
goto endit

::-----------------------------------------------------------------------------
::  Check arguments and select SET or CLEAR routine.  Unrecognized arguments
::  are ignored and SET is assumed.
::-----------------------------------------------------------------------------

:chkarg

if /I "%1" == "CLEAR" goto clrvar
goto setvar

::-----------------------------------------------------------------------------
::  Set variables for the day abbreviation (DAY), month number (MM), 
::  day number (DD) and 4-digit year (YYYY). 
::-----------------------------------------------------------------------------

:setvar

for /F "tokens=1-4 delims=/ " %%i IN ('date /t') DO (
set DT_DAY=%%i
set DT_MM=%%j
set DT_DD=%%k
set DT_YYYY=%%l)

goto endit

::-----------------------------------------------------------------------------
::  Clear all variables from the environment.
::-----------------------------------------------------------------------------

:clrvar
for %%v in (DT_DAY DT_MM DT_DD DT_YYYY) do set %%v=
goto endit

:endit

Android: java.lang.SecurityException: Permission Denial: start Intent

It's easy maybe you have error in the configuration.

For Example: Manifest.xml

enter image description here

But in my configuration have for default Activity .Splash

enter image description here

you need check this configuration and the file Manifest.xml

Good Luck

Reading file using relative path in python project

I was thundered when the following code worked.

import os

for file in os.listdir("../FutureBookList"):
    if file.endswith(".adoc"):
        filename, file_extension = os.path.splitext(file)
        print(filename)
        print(file_extension)
        continue
    else:
        continue

So, I checked the documentation and it says:

Changed in version 3.6: Accepts a path-like object.

path-like object:

An object representing a file system path. A path-like object is either a str or...

I did a little more digging and the following also works:

with open("../FutureBookList/file.txt") as file:
   data = file.read()

Using Laravel Homestead: 'no input file specified'

I was just struggling with same situation. Following solved the issue:

If you have directory structure like this:

folders:
    - map: /Users/me/code/exampleproject
      to: /home/vagrant/code/exampleproject

Just create 'public' folder within exampleproject on your host machine.

Is it a bad practice to use break in a for loop?

Far from bad practice, Python (and other languages?) extended the for loop structure so part of it will only be executed if the loop doesn't break.

for n in range(5):
    for m in range(3):
        if m >= n:
            print('stop!')
            break
        print(m, end=' ')
    else:
        print('finished.')

Output:

stop!
0 stop!
0 1 stop!
0 1 2 finished.
0 1 2 finished.

Equivalent code without break and that handy else:

for n in range(5):
    aborted = False
    for m in range(3):
        if not aborted:
            if m >= n:
                print('stop!')
                aborted = True
            else:            
                print(m, end=' ')
    if not aborted:
        print('finished.')

socket connect() vs bind()

The one liner : bind() to own address, connect() to remote address.

Quoting from the man page of bind()

bind() assigns the address specified by addr to the socket referred to by the file descriptor sockfd. addrlen specifies the size, in bytes, of the address structure pointed to by addr. Traditionally, this operation is called "assigning a name to a socket".

and, from the same for connect()

The connect() system call connects the socket referred to by the file descriptor sockfd to the address specified by addr.

To clarify,

  • bind() associates the socket with its local address [that's why server side binds, so that clients can use that address to connect to server.]
  • connect() is used to connect to a remote [server] address, that's why is client side, connect [read as: connect to server] is used.

How to check if activity is in foreground or in visible background?

One possible solution might be setting a flag while showing the system-dialog and then in the onStop method of the activity life-cycle, check for the flag, if true, finish the activity.

For example, if the system dialog is triggered by some buttonclick, then the onclick listener might be like

private OnClickListener btnClickListener = new OnClickListener() {

    @Override
    public void onClick(View v) {           
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setType("text/plain");
        CheckActivity.this.startActivity(Intent.createChooser(intent, "Complete action using"));
        checkFlag = true;  //flag used to check

    }
};

and in onstop of activity:

@Override
protected void onStop() {
    if(checkFlag){
        finish();
    }
    super.onStop();
}

Understanding Linux /proc/id/maps

memory mapping is not only used to map files into memory but is also a tool to request RAM from kernel. These are those inode 0 entries - your stack, heap, bss segments and more

ITextSharp insert text to an existing pdf

Here is a method that uses stamper and absolute coordinates showed in the different PDF clients (Adobe, FoxIt and etc. )

public static void AddTextToPdf(string inputPdfPath, string outputPdfPath, string textToAdd, System.Drawing.Point point)
    {
        //variables
        string pathin = inputPdfPath;
        string pathout = outputPdfPath;

        //create PdfReader object to read from the existing document
        using (PdfReader reader = new PdfReader(pathin))
        //create PdfStamper object to write to get the pages from reader 
        using (PdfStamper stamper = new PdfStamper(reader, new FileStream(pathout, FileMode.Create)))
        {
            //select two pages from the original document
            reader.SelectPages("1-2");

            //gettins the page size in order to substract from the iTextSharp coordinates
            var pageSize = reader.GetPageSize(1);

            // PdfContentByte from stamper to add content to the pages over the original content
            PdfContentByte pbover = stamper.GetOverContent(1);

            //add content to the page using ColumnText
            Font font = new Font();
            font.Size = 45;

            //setting up the X and Y coordinates of the document
            int x = point.X;
            int y = point.Y;

            y = (int) (pageSize.Height - y);

            ColumnText.ShowTextAligned(pbover, Element.ALIGN_CENTER, new Phrase(textToAdd, font), x, y, 0);
        }
    }

C++ pass an array by reference

Arrays can only be passed by reference, actually:

void foo(double (&bar)[10])
{
}

This prevents you from doing things like:

double arr[20];
foo(arr); // won't compile

To be able to pass an arbitrary size array to foo, make it a template and capture the size of the array at compile time:

template<typename T, size_t N>
void foo(T (&bar)[N])
{
    // use N here
}

You should seriously consider using std::vector, or if you have a compiler that supports c++11, std::array.