Programs & Examples On #Iomanip

Anything related to C++ I/O manipulators, i.e. special kinds of objects that alter the behavior of streams. Inserting a manipulator into an output stream or extracting one from an input stream provides an easy alternative for configuring specific aspects of the stream operations.

This declaration has no storage class or type specifier in C++

This is a mistake:

m.check(side);

That code has to go inside a function. Your class definition can only contain declarations and functions.

Classes don't "run", they provide a blueprint for how to make an object.

The line Message m; means that an Orderbook will contain Message called m, if you later create an Orderbook.

How to use setprecision in C++

#include <iomanip>
#include <iostream>

int main()
{
    double num1 = 3.12345678;
    std::cout << std::fixed << std::showpoint;
    std::cout << std::setprecision(2);
    std::cout << num1 << std::endl;
    return 0;
}

Error: Expression must have integral or unscoped enum type

Your variable size is declared as: float size;

You can't use a floating point variable as the size of an array - it needs to be an integer value.

You could cast it to convert to an integer:

float *temp = new float[(int)size];

Your other problem is likely because you're writing outside of the bounds of the array:

   float *temp = new float[size];

    //Getting input from the user
    for (int x = 1; x <= size; x++){
        cout << "Enter temperature " << x << ": ";

        // cin >> temp[x];
        // This should be:
        cin >> temp[x - 1];
    }

Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.

Dividing two integers to produce a float result

Cast the operands to floats:

float ans = (float)a / (float)b;

Why are elementwise additions much faster in separate loops than in a combined loop?

It's not because of a different code, but because of caching: RAM is slower than the CPU registers and a cache memory is inside the CPU to avoid to write the RAM every time a variable is changing. But the cache is not big as the RAM is, hence, it maps only a fraction of it.

The first code modifies distant memory addresses alternating them at each loop, thus requiring continuously to invalidate the cache.

The second code don't alternate: it just flow on adjacent addresses twice. This makes all the job to be completed in the cache, invalidating it only after the second loop starts.

"cannot be used as a function error"

This line is the problem:

int estimatedPopulation (int currentPopulation,
                         float growthRate (birthRate, deathRate))

Make it:

int estimatedPopulation (int currentPopulation, float birthRate, float deathRate)

instead and invoke the function with three arguments like

estimatePopulation( currentPopulation, birthRate, deathRate );

OR declare it with two arguments like:

int estimatedPopulation (int currentPopulation, float growthrt ) { ... }

and call it as

estimatedPopulation( currentPopulation, growthRate (birthRate, deathRate));

Edit:

Probably more important here - C++ (and C) names have scope. You can have two things named the same but not at the same time. In your particular case your grouthRate variable in the main() hides the function with the same name. So within main() you can only access grouthRate as float. On the other hand, outside of the main() you can only access that name as a function, since that automatic variable is only visible within the scope of main().

Just hope I didn't confuse you further :)

Best way to make a shell script daemon?

# double background your script to have it detach from the tty
# cf. http://www.linux-mag.com/id/5981 
(./program.sh &) & 

How to create a number picker dialog?

I have made a small demo of NumberPicker. This may not be perfect but you can use and modify the same.

public class MainActivity extends Activity implements NumberPicker.OnValueChangeListener
{
    private static TextView tv;
    static Dialog d ;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.textView1);
        Button b = (Button) findViewById(R.id.button11);
         b.setOnClickListener(new OnClickListener()
         {

            @Override
            public void onClick(View v) {
                 show();
            }
            });
           }
     @Override
    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {

         Log.i("value is",""+newVal);

     }

    public void show()
    {

         final Dialog d = new Dialog(MainActivity.this);
         d.setTitle("NumberPicker");
         d.setContentView(R.layout.dialog);
         Button b1 = (Button) d.findViewById(R.id.button1);
         Button b2 = (Button) d.findViewById(R.id.button2);
         final NumberPicker np = (NumberPicker) d.findViewById(R.id.numberPicker1);
         np.setMaxValue(100);
         np.setMinValue(0);
         np.setWrapSelectorWheel(false);
         np.setOnValueChangedListener(this);
         b1.setOnClickListener(new OnClickListener()
         {
          @Override
          public void onClick(View v) {
              tv.setText(String.valueOf(np.getValue()));
              d.dismiss();
           }    
          });
         b2.setOnClickListener(new OnClickListener()
         {
          @Override
          public void onClick(View v) {
              d.dismiss();
           }    
          });
       d.show();


    }
}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

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

    <Button
        android:id="@+id/button11"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="Open" />

</RelativeLayout>

dialog.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <NumberPicker
        android:id="@+id/numberPicker1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="64dp" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/numberPicker1"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="98dp"
        android:layout_toRightOf="@+id/numberPicker1"
        android:text="Cancel" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button2"
        android:layout_alignBottom="@+id/button2"
        android:layout_marginRight="16dp"
        android:layout_toLeftOf="@+id/numberPicker1"
        android:text="Set" />

</RelativeLayout>

Edit:

under res/values/dimens.xml

<resources>

    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>

</resources>

MySQL query to get column names?

Edit: Today I learned the better way of doing this. Please see ircmaxell's answer.


Parse the output of SHOW COLUMNS FROM table;

Here's more about it here: http://dev.mysql.com/doc/refman/5.0/en/show-columns.html

Maven - Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.4.1:clean

In my case, it was Subversion, TortoiseSVN clinging to those files, so I just clicked on SVN in the Eclipse menu and then disconnect. Worked for me.

Access elements in json object like an array

I found a straight forward way of solving this, with the use of JSON.parse.

Let's assume the json below is inside the variable jsontext.

[
  ["Blankaholm", "Gamleby"],
  ["2012-10-23", "2012-10-22"],
  ["Blankaholm. Under natten har det varit inbrott", "E22 i med Gamleby. Singelolycka. En bilist har.],
  ["57.586174","16.521841"], ["57.893162","16.406090"]
]

The solution is this:

var parsedData = JSON.parse(jsontext);

Now I can access the elements the following way:

var cities = parsedData[0];

Avoid duplicates in INSERT INTO SELECT query in SQL Server

From SQL Server you can set a Unique key index on the table for (Columns that needs to be unique)

From sql server right click on the table design select Indexes/Keys

Select column(s) that will be not duplicate , then type Unique Key

How to set the custom border color of UIView programmatically?

Swift 5.2, UIView+Extension

extension UIView {
    public func addViewBorder(borderColor:CGColor,borderWith:CGFloat,borderCornerRadius:CGFloat){
        self.layer.borderWidth = borderWith
        self.layer.borderColor = borderColor
        self.layer.cornerRadius = borderCornerRadius

    }
}

You used this extension;

yourView.addViewBorder(borderColor: #colorLiteral(red: 0.6, green: 0.6, blue: 0.6, alpha: 1), borderWith: 1.0, borderCornerRadius: 20)

How do I dynamically set HTML5 data- attributes using react?

Note - if you want to pass a data attribute to a React Component, you need to handle them a little differently than other props.

2 options

Don't use camel case

<Option data-img-src='value' ... />

And then in the component, because of the dashes, you need to refer to the prop in quotes.

// @flow
class Option extends React.Component {

  props: {
    'data-img-src': string
  }

And when you refer to it later, you don't use the dot syntax

  render () {
    return (
      <option data-img-src={this.props['data-img-src']} >...</option>
    )
  }
}

Or use camel case

<Option dataImgSrc='value' ... />

And then in the component, you need to convert.

// @flow
class Option extends React.Component {

  props: {
    dataImgSrc: string
  }

And when you refer to it later, you don't use the dot syntax

  render () {
    return (
      <option data-img-src={this.props.dataImgSrc} >...</option>
    )
  }
}

Mainly just realize data- attributes and aria- attributes are treated specially. You are allowed to use hyphens in the attribute name in those two cases.

Oracle to_date, from mm/dd/yyyy to dd-mm-yyyy

select to_char(to_date('1/21/2000','mm/dd/yyyy'),'dd-mm-yyyy') from dual

How is the AND/OR operator represented as in Regular Expressions?

Or you can use this:

^(?:part[12]|(part)1,\12)$

Get list of a class' instance methods

$ irb --simple-prompt

class TestClass
  def method1
  end

  def method2
  end

  def method3
  end
end

tc_list = TestClass.instance_methods(false)
#[:method1, :method2, :method3]
puts tc_list
#method1
#method2
#method3

How many significant digits do floats and doubles have in java?

Floating point numbers are encoded using an exponential form, that is something like m * b ^ e, i.e. not like integers at all. The question you ask would be meaningful in the context of fixed point numbers. There are numerous fixed point arithmetic libraries available.

Regarding floating point arithmetic: The number of decimal digits depends on the presentation and the number system. For example there are periodic numbers (0.33333) which do not have a finite presentation in decimal but do have one in binary and vice versa.

Also it is worth mentioning that floating point numbers up to a certain point do have a difference larger than one, i.e. value + 1 yields value, since value + 1 can not be encoded using m * b ^ e, where m, b and e are fixed in length. The same happens for values smaller than 1, i.e. all the possible code points do not have the same distance.

Because of this there is no precision of exactly n digits like with fixed point numbers, since not every number with n decimal digits does have a IEEE encoding.

There is a nearly obligatory document which you should read then which explains floating point numbers: What every computer scientist should know about floating point arithmetic.

Passing variables through handlebars partial

This is very possible if you write your own helper. We are using a custom $ helper to accomplish this type of interaction (and more):

/*///////////////////////

Adds support for passing arguments to partials. Arguments are merged with 
the context for rendering only (non destructive). Use `:token` syntax to 
replace parts of the template path. Tokens are replace in order.

USAGE: {{$ 'path.to.partial' context=newContext foo='bar' }}
USAGE: {{$ 'path.:1.:2' replaceOne replaceTwo foo='bar' }}

///////////////////////////////*/

Handlebars.registerHelper('$', function(partial) {
    var values, opts, done, value, context;
    if (!partial) {
        console.error('No partial name given.');
    }
    values = Array.prototype.slice.call(arguments, 1);
    opts = values.pop();
    while (!done) {
        value = values.pop();
        if (value) {
            partial = partial.replace(/:[^\.]+/, value);
        }
        else {
            done = true;
        }
    }
    partial = Handlebars.partials[partial];
    if (!partial) {
        return '';
    }
    context = _.extend({}, opts.context||this, _.omit(opts, 'context', 'fn', 'inverse'));
    return new Handlebars.SafeString( partial(context) );
});

How to create jobs in SQL Server Express edition

SQL Server Express editions are limited in some ways - one way is that they don't have the SQL Agent that allows you to schedule jobs.

There are a few third-party extensions that provide that capability - check out e.g.:

How to get the caret column (not pixels) position in a textarea, in characters, from the start?

If you don't have to support IE, you can use selectionStart and selectionEnd attributes of textarea.

To get caret position just use selectionStart:

function getCaretPosition(textarea) {
  return textarea.selectionStart
}

To get the strings surrounding the selection, use following code:

function getSurroundingSelection(textarea) {
  return [textarea.value.substring(0, textarea.selectionStart)
         ,textarea.value.substring(textarea.selectionStart, textarea.selectionEnd)
         ,textarea.value.substring(textarea.selectionEnd, textarea.value.length)]
}

Demo on JSFiddle.

See also HTMLTextAreaElement docs.

javascript scroll event for iPhone/iPad?

I was able to get a great solution to this problem with iScroll, with the feel of momentum scrolling and everything https://github.com/cubiq/iscroll The github doc is great, and I mostly followed it. Here's the details of my implementation.

HTML: I wrapped the scrollable area of my content in some divs that iScroll can use:

<div id="wrapper">
  <div id="scroller">
    ... my scrollable content
  </div>
</div>

CSS: I used the Modernizr class for "touch" to target my style changes only to touch devices (because I only instantiated iScroll on touch).

.touch #wrapper {
  position: absolute;
  z-index: 1;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  overflow: hidden;
}
.touch #scroller {
  position: absolute;
  z-index: 1;
  width: 100%;
}

JS: I included iscroll-probe.js from the iScroll download, and then initialized the scroller as below, where updatePosition is my function that reacts to the new scroll position.

# coffeescript
if Modernizr.touch
  myScroller = new IScroll('#wrapper', probeType: 3)
  myScroller.on 'scroll', updatePosition
  myScroller.on 'scrollEnd', updatePosition

You have to use myScroller to get the current position now, instead of looking at the scroll offset. Here is a function taken from http://markdalgleish.com/presentations/embracingtouch/ (a super helpful article, but a little out of date now)

function getScroll(elem, iscroll) {   
  var x, y;

  if (Modernizr.touch && iscroll) {
    x = iscroll.x * -1;
    y = iscroll.y * -1;   
  } else {
    x = elem.scrollTop;
    y = elem.scrollLeft;   
  }

  return {x: x, y: y}; 
}

The only other gotcha was occasionally I would lose part of my page that I was trying to scroll to, and it would refuse to scroll. I had to add in some calls to myScroller.refresh() whenever I changed the contents of the #wrapper, and that solved the problem.

EDIT: Another gotcha was that iScroll eats all the "click" events. I turned on the option to have iScroll emit a "tap" event and handled those instead of "click" events. Thankfully I didn't need much clicking in the scroll area, so this wasn't a big deal.

Calling a function of a module by using its name (a string)

For what it's worth, if you needed to pass the function (or class) name and app name as a string, then you could do this:

myFnName  = "MyFn"
myAppName = "MyApp"
app = sys.modules[myAppName]
fn  = getattr(app,myFnName)

Print a list of space-separated elements in Python 3

You can apply the list as separate arguments:

print(*L)

and let print() take care of converting each element to a string. You can, as always, control the separator by setting the sep keyword argument:

>>> L = [1, 2, 3, 4, 5]
>>> print(*L)
1 2 3 4 5
>>> print(*L, sep=', ')
1, 2, 3, 4, 5
>>> print(*L, sep=' -> ')
1 -> 2 -> 3 -> 4 -> 5

Unless you need the joined string for something else, this is the easiest method. Otherwise, use str.join():

joined_string = ' '.join([str(v) for v in L])
print(joined_string)
# do other things with joined_string

Note that this requires manual conversion to strings for any non-string values in L!

C++ convert from 1 char to string?

All of

std::string s(1, c); std::cout << s << std::endl;

and

std::cout << std::string(1, c) << std::endl;

and

std::string s; s.push_back(c); std::cout << s << std::endl;

worked for me.

How do I convert a Django QuerySet into list of dicts?

If you need native data types for some reason (e.g. JSON serialization) this is my quick 'n' dirty way to do it:

data = [{'id': blog.pk, 'name': blog.name} for blog in blogs]

As you can see building the dict inside the list is not really DRY so if somebody knows a better way ...

Telegram Bot - how to get a group chat id?

After mid-2018:
1:) Invite @getidsbot or @RawDataBot to your group and get your group id from the chat id field.

Message
 + message_id: 338
 + from
 ?  + id: *****
 ?  + is_bot: false
 ?  + first_name: ???
 ?  + username: ******
 ?  + language_code: en
 + chat
 ?  + id: -1001118554477    // This is Your Group id
 ?  + title: Test Group
 ?  + type: supergroup
 + date: 1544948900
 + text: A

2:) use an unofficial Messenger like Plus Messenger and see your group id in group/channel info.

Before mid-2018: (don't Use)
1: Goto (https://web.telegram.org)
2: Goto your Gorup and Find your link of Gorup(https://web.telegram.org/#/im?p=g154513121)
3: Copy That number after g and put a (-) Before That -154513121
4: Send Your Message to Gorup bot.sendMessage(-154513121, "Hi")
I Tested Now and Work like a Charm

Delete all lines starting with # or ; in Notepad++

In Notepad++, you can use the Mark tab in the Find dialogue to Bookmark all lines matching your query which can be regex or normal (wildcard).

Then use Search > Bookmark > Remove Bookmarked Lines.

Create a Path from String in Java7

Even when the question is regarding Java 7, I think it adds value to know that from Java 11 onward, there is a static method in Path class that allows to do this straight away:

With all the path in one String:

Path.of("/tmp/foo");

With the path broken down in several Strings:

Path.of("/tmp","foo");

Arduino Nano - "avrdude: ser_open():system can't open device "\\.\COM1": the system cannot find the file specified"

Changing the port in Device Manager works for me. I was also able to fix it by finding the port that Arduino was using and then select it from the Adruion IDE from tools menu Tools>Port>Com Port

Adruino IDE

Does the join order matter in SQL?

For INNER joins, no, the order doesn't matter. The queries will return same results, as long as you change your selects from SELECT * to SELECT a.*, b.*, c.*.


For (LEFT, RIGHT or FULL) OUTER joins, yes, the order matters - and (updated) things are much more complicated.

First, outer joins are not commutative, so a LEFT JOIN b is not the same as b LEFT JOIN a

Outer joins are not associative either, so in your examples which involve both (commutativity and associativity) properties:

a LEFT JOIN b 
    ON b.ab_id = a.ab_id
  LEFT JOIN c
    ON c.ac_id = a.ac_id

is equivalent to:

a LEFT JOIN c 
    ON c.ac_id = a.ac_id
  LEFT JOIN b
    ON b.ab_id = a.ab_id

but:

a LEFT JOIN b 
    ON  b.ab_id = a.ab_id
  LEFT JOIN c
    ON  c.ac_id = a.ac_id
    AND c.bc_id = b.bc_id

is not equivalent to:

a LEFT JOIN c 
    ON  c.ac_id = a.ac_id
  LEFT JOIN b
    ON  b.ab_id = a.ab_id
    AND b.bc_id = c.bc_id

Another (hopefully simpler) associativity example. Think of this as (a LEFT JOIN b) LEFT JOIN c:

a LEFT JOIN b 
    ON b.ab_id = a.ab_id          -- AB condition
 LEFT JOIN c
    ON c.bc_id = b.bc_id          -- BC condition

This is equivalent to a LEFT JOIN (b LEFT JOIN c):

a LEFT JOIN  
    b LEFT JOIN c
        ON c.bc_id = b.bc_id          -- BC condition
    ON b.ab_id = a.ab_id          -- AB condition

only because we have "nice" ON conditions. Both ON b.ab_id = a.ab_id and c.bc_id = b.bc_id are equality checks and do not involve NULL comparisons.

You can even have conditions with other operators or more complex ones like: ON a.x <= b.x or ON a.x = 7 or ON a.x LIKE b.x or ON (a.x, a.y) = (b.x, b.y) and the two queries would still be equivalent.

If however, any of these involved IS NULL or a function that is related to nulls like COALESCE(), for example if the condition was b.ab_id IS NULL, then the two queries would not be equivalent.

Carousel with Thumbnails in Bootstrap 3.0

  1. Use the carousel's indicators to display thumbnails.
  2. Position the thumbnails outside of the main carousel with CSS.
  3. Set the maximum height of the indicators to not be larger than the thumbnails.
  4. Whenever the carousel has slid, update the position of the indicators, positioning the active indicator in the middle of the indicators.

I'm using this on my site (for example here), but I'm using some extra stuff to do lazy loading, meaning extracting the code isn't as straightforward as I would like it to be for putting it in a fiddle.

Also, my templating engine is smarty, but I'm sure you get the idea.

The meat...

Updating the indicators:

<ol class="carousel-indicators">
    {assign var='walker' value=0}
    {foreach from=$item["imagearray"] key="key" item="value"}
        <li data-target="#myCarousel" data-slide-to="{$walker}"{if $walker == 0} class="active"{/if}>
            <img src='http://farm{$value["farm"]}.static.flickr.com/{$value["server"]}/{$value["id"]}_{$value["secret"]}_s.jpg'>
        </li>

        {assign var='walker' value=1 + $walker}
    {/foreach}
</ol>

Changing the CSS related to the indicators:

.carousel-indicators {
    bottom:-50px;
    height: 36px;
    overflow-x: hidden;
    white-space: nowrap;
}

.carousel-indicators li {
    text-indent: 0;
    width: 34px !important;
    height: 34px !important;
    border-radius: 0;
}

.carousel-indicators li img {
    width: 32px;
    height: 32px;
    opacity: 0.5;
}

.carousel-indicators li:hover img, .carousel-indicators li.active img {
    opacity: 1;
}

.carousel-indicators .active {
    border-color: #337ab7;
}

When the carousel has slid, update the list of thumbnails:

$('#myCarousel').on('slid.bs.carousel', function() {
    var widthEstimate = -1 * $(".carousel-indicators li:first").position().left + $(".carousel-indicators li:last").position().left + $(".carousel-indicators li:last").width(); 
    var newIndicatorPosition = $(".carousel-indicators li.active").position().left + $(".carousel-indicators li.active").width() / 2;
    var toScroll = newIndicatorPosition + indicatorPosition;
    var adjustedScroll = toScroll - ($(".carousel-indicators").width() / 2);
    if (adjustedScroll < 0)
        adjustedScroll = 0;

    if (adjustedScroll > widthEstimate - $(".carousel-indicators").width())
        adjustedScroll = widthEstimate - $(".carousel-indicators").width();

    $('.carousel-indicators').animate({ scrollLeft: adjustedScroll }, 800);

    indicatorPosition = adjustedScroll;
});

And, when your page loads, set the initial scroll position of the thumbnails:

var indicatorPosition = 0;

Why would one omit the close tag?

It's pretty useful not to let the closing ?> in.

The file stays valid to PHP (not a syntax error) and as @David Dorward said it allows to avoid having white space / break-line (anything that can send a header to the browser) after the ?>.

For example,

<?
    header("Content-type: image/png");
    $img = imagecreatetruecolor ( 10, 10);
    imagepng ( $img);
?>
[space here]
[break line here]

won't be valid.

But

<?
    header("Content-type: image/png");
    $img = imagecreatetruecolor ( 10, 10 );
    imagepng ( $img );

will.

For once, you must be lazy to be secure.

Execute bash script from URL

source <(curl -s http://mywebsite.com/myscript.txt)

ought to do it. Alternately, leave off the initial redirection on yours, which is redirecting standard input; bash takes a filename to execute just fine without redirection, and <(command) syntax provides a path.

bash <(curl -s http://mywebsite.com/myscript.txt)

It may be clearer if you look at the output of echo <(cat /dev/null)

Gradle proxy configuration

There are 2 ways for using Gradle behind a proxy :

Add arguments in command line

(From Guillaume Berche's post)

Add these arguments in your gradle command :

-Dhttp.proxyHost=your_proxy_http_host -Dhttp.proxyPort=your_proxy_http_port

or these arguments if you are using https :

-Dhttps.proxyHost=your_proxy_https_host -Dhttps.proxyPort=your_proxy_https_port

Add lines in gradle configuration file

in gradle.properties add the following lines :

systemProp.http.proxyHost=your_proxy_http_host
systemProp.http.proxyPort=your_proxy_http_port
systemProp.https.proxyHost=your_proxy_https_host
systemProp.https.proxyPort=your_proxy_https_port

(for gradle.properties file location, please refer to official documentation https://docs.gradle.org/current/userguide/build_environment.html


EDIT : as said by @Joost : A small but important detail that I initially overlooked: notice that the actual host name does NOT contain http:// protocol part of the URL...

In Python, how do I split a string and keep the separators?

I had a similar issue trying to split a file path and struggled to find a simple answer. This worked for me and didn't involve having to substitute delimiters back into the split text:

my_path = 'folder1/folder2/folder3/file1'

import re

re.findall('[^/]+/|[^/]+', my_path)

returns:

['folder1/', 'folder2/', 'folder3/', 'file1']

Google Maps API v2: How to make markers clickable?

I have edited the given above example...

public class YourActivity extends implements OnMarkerClickListener
{
    ......

    private void setMarker()
    {
        .......
        googleMap.setOnMarkerClickListener(this);

        myMarker = googleMap.addMarker(new MarkerOptions()
                    .position(latLng)
                    .title("My Spot")
                    .snippet("This is my spot!")
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
        ......
    }

    @Override
    public boolean onMarkerClick(Marker marker) {

       Toast.makeText(this,marker.getTitle(),Toast.LENGTH_LONG).show();
    }
}

Use .htaccess to redirect HTTP to HTTPs

This is tested and safe to use

Why?: When Wordpress editing your re-write rules, so make sure your HTTPS rule should not be removed! so this is no conflict with native Wordpress rules.

<IfModule mod_rewrite.c>
   RewriteCond %{HTTPS} !=on
   RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L]
</IfModule>

# BEGIN WordPress
<IfModule mod_rewrite.c>
  #Your our Wordpress rewrite rules...
</IfModule>
# END WordPress

Note: You have to change WordPress Address & Site Address urls to https:// in General Settings also (wp-admin/options-general.php)

Regular expression to get a string between two strings in Javascript

If the data is on multiple lines then you may have to use the following,

/My cow ([\s\S]*)milk/gm

My cow always gives 
milk

Regex 101 example

List all kafka topics

You need to start the zookeeper server first. So first go to kafka/bin/windows and run

zookeeper-server-start.bat ../../config/zookeeper.properties

then in the same folder with a new cmd windows start the kafka servers by running

kafka-server-start.bat ../../config/server.properties

Note: if you starting it for the first time then there are certain changes to be made in these files

then inside kafka/bin/windows run

kafka-topics.bat --zookeeper localhost:2181 --list

to list down all the topics existing.

How to get ASCII value of string in C#

This should work:

string s = "9quali52ty3";
byte[] ASCIIValues = Encoding.ASCII.GetBytes(s);
foreach(byte b in ASCIIValues) {
    Console.WriteLine(b);
}

How to convert InputStream to FileInputStream

Use ClassLoader#getResource() instead if its URI represents a valid local disk file system path.

URL resource = classLoader.getResource("resource.ext");
File file = new File(resource.toURI());
FileInputStream input = new FileInputStream(file);
// ...

If it doesn't (e.g. JAR), then your best bet is to copy it into a temporary file.

Path temp = Files.createTempFile("resource-", ".ext");
Files.copy(classLoader.getResourceAsStream("resource.ext"), temp, StandardCopyOption.REPLACE_EXISTING);
FileInputStream input = new FileInputStream(temp.toFile());
// ...

That said, I really don't see any benefit of doing so, or it must be required by a poor helper class/method which requires FileInputStream instead of InputStream. If you can, just fix the API to ask for an InputStream instead. If it's a 3rd party one, by all means report it as a bug. I'd in this specific case also put question marks around the remainder of that API.

How to check if a given directory exists in Ruby

You can also use Dir::exist? like so:

Dir.exist?('Directory Name')

Returns true if the 'Directory Name' is a directory, false otherwise.1

What database does Google use?

Google services have a polyglot persistence architecture. BigTable is leveraged by most of its services like YouTube, Google Search, Google Analytics etc. The search service initially used MapReduce for its indexing infrastructure but later transitioned to BigTable during the Caffeine release.

Google Cloud datastore has over 100 applications in production at Google both facing internal and external users. Applications like Gmail, Picasa, Google Calendar, Android Market & AppEngine use Cloud Datastore & Megastore.

Google Trends use MillWheel for stream processing. Google Ads initially used MySQL later migrated to F1 DB - a custom written distributed relational database. Youtube uses MySQL with Vitess. Google stores exabytes of data across the commodity servers with the help of the Google File System.

Source: Google Databases: How Do Google Services Store Petabyte-Exabyte Scale Data?

YouTube Database – How Does It Store So Many Videos Without Running Out Of Storage Space?

enter image description here

Get IP address of an interface on Linux

Try this:

#include <stdio.h>
#include <unistd.h>
#include <string.h> /* for strncpy */

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <arpa/inet.h>

int
main()
{
 int fd;
 struct ifreq ifr;

 fd = socket(AF_INET, SOCK_DGRAM, 0);

 /* I want to get an IPv4 IP address */
 ifr.ifr_addr.sa_family = AF_INET;

 /* I want IP address attached to "eth0" */
 strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1);

 ioctl(fd, SIOCGIFADDR, &ifr);

 close(fd);

 /* display result */
 printf("%s\n", inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));

 return 0;
}

The code sample is taken from here.

Check if a column contains text using SQL

Try LIKE construction, e.g. (assuming StudentId is of type Char, VarChar etc.)

  select * 
    from Students
   where StudentId like '%' || TEXT || '%' -- <- TEXT - text to contain

How to make the main content div fill height of screen with css

This allows for a centered content body with min-width for my forms to not collapse funny:

html {
    overflow-y: scroll;
    height: 100%;
    margin: 0px auto;
    padding: 0;
}

body {
    height: 100%;
    margin: 0px auto;
    max-width: 960px;
    min-width: 750px;
    padding: 0;
}
div#footer {
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    height: 60px;
}

div#wrapper {
    height: auto !important;
    min-height: 100%;
    height: 100%;
    position: relative;
    overflow: hidden;
}

div#pageContent {
    padding-bottom: 60px;
}

div#header {
    width: 100%;
}

And my layout page looks like:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<head>
    <title></title>
</head>
<body>
<div id="wrapper">
        <div id="header"></div>
        <div id="pageContent"></div>
        <div id="footer"></div>
    </div>
</body>
</html>

Example here: http://data.nwtresearch.com/

One more note, if you want the full page background like the code you added looks like, remove the height: auto !important; from the wrapper div: http://jsfiddle.net/mdares/a8VVw/

failed to push some refs to [email protected]

Make sure you’re pushing the right branch. I wasn’t on master and kept wondering why it was complaining :P

force browsers to get latest js and css files in asp.net application

For ASP.NET pages I am using the following

BEFORE

<script src="/Scripts/pages/common.js" type="text/javascript"></script>

AFTER (force reload)

 <script src="/Scripts/pages/common.js?ver<%=DateTime.Now.Ticks.ToString()%>" type="text/javascript"></script>

Adding the DateTime.Now.Ticks works very well.

How to use Oracle ORDER BY and ROWNUM correctly?

The where statement gets executed before the order by. So, your desired query is saying "take the first row and then order it by t_stamp desc". And that is not what you intend.

The subquery method is the proper method for doing this in Oracle.

If you want a version that works in both servers, you can use:

select ril.*
from (select ril.*, row_number() over (order by t_stamp desc) as seqnum
      from raceway_input_labo ril
     ) ril
where seqnum = 1

The outer * will return "1" in the last column. You would need to list the columns individually to avoid this.

What does --net=host option in Docker command really do?

After the docker installation you have 3 networks by default:

docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
f3be8b1ef7ce        bridge              bridge              local
fbff927877c1        host                host                local
023bb5940080        none                null                local

I'm trying to keep this simple. So if you start a container by default it will be created inside the bridge (docker0) network.

$ docker run -d jenkins
1498e581cdba        jenkins             "/bin/tini -- /usr..."   3 minutes ago       Up 3 minutes        8080/tcp, 50000/tcp   friendly_bell

In the dockerfile of jenkins the ports 8080 and 50000 are exposed. Those ports are opened for the container on its bridge network. So everything inside that bridge network can access the container on port 8080 and 50000. Everything in the bridge network is in the private range of "Subnet": "172.17.0.0/16", If you want to access them from the outside you have to map the ports with -p 8080:8080. This will map the port of your container to the port of your real server (the host network). So accessing your server on 8080 will route to your bridgenetwork on port 8080.

Now you also have your host network. Which does not containerize the containers networking. So if you start a container in the host network it will look like this (it's the first one):

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                 NAMES
1efd834949b2        jenkins             "/bin/tini -- /usr..."   6 minutes ago       Up 6 minutes                              eloquent_panini
1498e581cdba        jenkins             "/bin/tini -- /usr..."   10 minutes ago      Up 10 minutes       8080/tcp, 50000/tcp   friendly_bell

The difference is with the ports. Your container is now inside your host network. So if you open port 8080 on your host you will acces the container immediately.

$ sudo iptables -I INPUT 5 -p tcp -m tcp --dport 8080 -j ACCEPT

I've opened port 8080 in my firewall and when I'm now accesing my server on port 8080 I'm accessing my jenkins. I think this blog is also useful to understand it better.

Tool to monitor HTTP, TCP, etc. Web Service traffic

JMeter's built-in proxy may be used to record all HTTP request/response information.

Firefox "Live HTTP headers" plugin may be used to see what is happening on the browser side when sending/receiving request.

Firefox "Tamper data" plugin may be useful when you need to intercept and modify request.

Easiest way to convert int to string in C++

I usually use the following method:

#include <sstream>

template <typename T>
  std::string NumberToString ( T Number )
  {
     std::ostringstream ss;
     ss << Number;
     return ss.str();
  }

It is described in details here.

How do I set the visibility of a text box in SSRS using an expression?

the rdl file content:

<Visibility><Hidden>=Parameters!casetype.Value=300</Hidden></Visibility>

so the text box will hidden, if your expression is true.

Chart won't update in Excel (2007)

I found that by creating the chart in a separate worksheet any updates will apply. HTH

How to read barcodes with the camera on Android?

I had an issue with the parseActivityForResult arguments. I got this to work:

package JMA.BarCodeScanner;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class JMABarcodeScannerActivity extends Activity {

    Button captureButton;
    TextView tvContents;
    TextView tvFormat;
    Activity activity;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        activity = this;
        captureButton = (Button)findViewById(R.id.capture);
        captureButton.setOnClickListener(listener);
        tvContents = (TextView)findViewById(R.id.tvContents);
        tvFormat = (TextView)findViewById(R.id.tvFormat);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent intent) 
    {  
        switch (requestCode) 
        {
            case IntentIntegrator.REQUEST_CODE:
            if (resultCode == Activity.RESULT_OK) 
            {
                IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);

                if (intentResult != null) 
                {
                   String contents = intentResult.getContents();
                   String format = intentResult.getFormatName();
                   tvContents.setText(contents.toString());
                   tvFormat.setText(format.toString());

                   //this.elemQuery.setText(contents);
                   //this.resume = false;
                   Log.d("SEARCH_EAN", "OK, EAN: " + contents + ", FORMAT: " + format);
                } else {
                    Log.e("SEARCH_EAN", "IntentResult je NULL!");
                }
            } 
            else if (resultCode == Activity.RESULT_CANCELED) {
                Log.e("SEARCH_EAN", "CANCEL");
            }
        }
    }

    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             IntentIntegrator integrator = new IntentIntegrator(activity);
             integrator.initiateScan();
        }
    };
}

Latyout for Activity:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button
        android:id="@+id/capture"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Take a Picture"/>

    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/tvContents"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/tvFormat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

Read only the first line of a file?

fline=open("myfile").readline().rstrip()

Concat strings by & and + in VB.Net

As your question confirms, they are different: & is ONLY string concatenation, + is overloaded with both normal addition and concatenation.

In your example:

  • because one of the operands to + is an integer VB attempts to convert the string to a integer, and as your string is not numeric it throws; and

  • & only works with strings so the integer is converted to a string.

How to generate a random string of a fixed length in Go?

how random count in :

count, one := big.NewInt(0), big.NewInt(1)
count.SetString("100000000000000000000000", 10)

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly

You need to set up SSH keys.

This GitHub page explains how to generate keys.

If you have an existing key, you copy $HOME/.ssh/id_rsa.pub and paste it into the GitHub SSH settings page.

Difference between & and && in Java?

&& == logical AND

& = bitwise AND

React.js: onChange event for contentEditable

Edit: See Sebastien Lorber's answer which fixes a bug in my implementation.


Use the onInput event, and optionally onBlur as a fallback. You might want to save the previous contents to prevent sending extra events.

I'd personally have this as my render function.

var handleChange = function(event){
    this.setState({html: event.target.value});
}.bind(this);

return (<ContentEditable html={this.state.html} onChange={handleChange} />);

jsbin

Which uses this simple wrapper around contentEditable.

var ContentEditable = React.createClass({
    render: function(){
        return <div 
            onInput={this.emitChange} 
            onBlur={this.emitChange}
            contentEditable
            dangerouslySetInnerHTML={{__html: this.props.html}}></div>;
    },
    shouldComponentUpdate: function(nextProps){
        return nextProps.html !== this.getDOMNode().innerHTML;
    },
    emitChange: function(){
        var html = this.getDOMNode().innerHTML;
        if (this.props.onChange && html !== this.lastHtml) {

            this.props.onChange({
                target: {
                    value: html
                }
            });
        }
        this.lastHtml = html;
    }
});

else & elif statements not working in Python

Remember that by default the return value from the input will be a string and not an integer. You cannot compare strings with booleans like <, >, =>, <= (unless you are comparing the length). Therefore your code should look like this:

number = 23
guess = int(input('Enter a number: '))  # The var guess will be an integer

if guess == number:
    print('Congratulations! You guessed it.')

elif guess != number:
    print('Wrong Number')

Keyboard shortcut to clear cell output in Jupyter notebook

Add following at start of cell and run it:

from IPython.display import clear_output
clear_output(wait=True)

Remove Item in Dictionary based on Value

Here is a method you can use:

    public static void RemoveAllByValue<K, V>(this Dictionary<K, V> dictionary, V value)
    {
        foreach (var key in dictionary.Where(
                kvp => EqualityComparer<V>.Default.Equals(kvp.Value, value)).
                Select(x => x.Key).ToArray())
            dictionary.Remove(key);
    }

Appropriate datatype for holding percent values?

Use numeric(n,n) where n has enough resolution to round to 1.00. For instance:

declare @discount numeric(9,9)
    , @quantity int
select @discount = 0.999999999
    , @quantity = 10000

select convert(money, @discount * @quantity)

What does the term "Tuple" Mean in Relational Databases?

tuple = 1 record; n-tuple = ordered list of 'n' records; Elmasri Navathe book (page 198 3rd edition).

record = either ordered or unordered.

Should I use 'border: none' or 'border: 0'?

You may simply use both as per the specification kindly provided by Oli.

I always use border:0 none;.

Though there is no harm in specifying them seperately and some browsers will parse the CSS faster if you do use the legacy CSS1 property calls.

Though border:0; will normally default the border style to none, I have however noticed some browsers enforcing their default border style which can strangely overwrite border:0;.

Absolute and Flexbox in React Native

Ok, solved my problem, if anyone is passing by here is the answer:

Just had to add left: 0, and top: 0, to the styles, and yes, I'm tired.

position: 'absolute',
left:     0,
top:      0,

Edit Crystal report file without Crystal Report software

I wouldn't have thought so.

If you have Visual Studio you could edit them through that. Some versions of Visual Studio has Crystal Reports shipped with them.

If not, you will have to find someone who has Crystal Reports and ask then nicely to amend them for you. Or buy Crystal Reports!

How to disable horizontal scrolling of UIScrollView?

In my case the width of the contentView was greater than the width of UIScrollView and that was the reason for unwanted horizontal scrolling. I solved it by setting the width of contentView equal to width of UIScrollView.

Hope it helps someone

Changing the resolution of a VNC session in linux

As this question comes up first on Google I thought I'd share a solution using TigerVNC which is the default these days.

xrandr allows selecting the display modes (a.k.a resolutions) however due to modelines being hard coded any additional modeline such as "2560x1600" or "1600x900" would need to be added into the code. I think the developers who wrote the code are much smarter and the hard coded list is just a sample of values. It leads to the conclusion that there must be a way to add custom modelines and man xrandr confirms it.

With that background if the goal is to share a VNC session between two computers with the above resolutions and assuming that the VNC server is the computer with the resolution of "1600x900":

  1. Start a VNC session with a geometry matching the physical display:

    $ vncserver -geometry 1600x900 :1
    
  2. On the "2560x1600" computer start the VNC viewer (I prefer Remmina) and connect to the remote VNC session:

    host:5901
    
  3. Once inside the VNC session start up a terminal window.

  4. Confirm that the new geometry is available in the VNC session:

    $ xrandr
    Screen 0: minimum 32 x 32, current 1600 x 900, maximum 32768 x 32768
    VNC-0 connected 1600x900+0+0 0mm x 0mm
       1600x900      60.00 +
       1920x1200     60.00  
       1920x1080     60.00  
       1600x1200     60.00  
       1680x1050     60.00  
       1400x1050     60.00  
       1360x768      60.00  
       1280x1024     60.00  
       1280x960      60.00  
       1280x800      60.00  
       1280x720      60.00  
       1024x768      60.00  
       800x600       60.00  
       640x480       60.00  
    

    and you'll notice the screen being quite small.

  5. List the modeline (see xrandr article in ArchLinux wiki) for the "2560x1600" resolution:

    $ cvt 2560 1600
    # 2560x1600 59.99 Hz (CVT 4.10MA) hsync: 99.46 kHz; pclk: 348.50 MHz
    Modeline "2560x1600_60.00"  348.50  2560 2760 3032 3504  1600 1603 1609 1658 -hsync +vsync
    

    or if the monitor is old get the GTF timings:

    $ gtf 2560 1600 60
    # 2560x1600 @ 60.00 Hz (GTF) hsync: 99.36 kHz; pclk: 348.16 MHz
    Modeline "2560x1600_60.00"  348.16  2560 2752 3032 3504  1600 1601 1604 1656 -HSync +Vsync
    
  6. Add the new modeline to the current VNC session:

    $ xrandr --newmode "2560x1600_60.00"  348.16  2560 2752 3032 3504  1600 1601 1604 1656 -HSync +Vsync
    
  7. In the above xrandr output look for the display name on the second line:

    VNC-0 connected 1600x900+0+0 0mm x 0mm
    
  8. Bind the new modeline to the current VNC virtual monitor:

    $ xrandr --addmode VNC-0 "2560x1600_60.00"
    
  9. Use it:

    $ xrandr -s "2560x1600_60.00"
    

VBA: How to delete filtered rows in Excel?

Use SpecialCells to delete only the rows that are visible after autofiltering:

ActiveSheet.Range("$A$1:$I$" & lines).SpecialCells _
    (xlCellTypeVisible).EntireRow.Delete

If you have a header row in your range that you don't want to delete, add an offset to the range to exclude it:

ActiveSheet.Range("$A$1:$I$" & lines).Offset(1, 0).SpecialCells _
    (xlCellTypeVisible).EntireRow.Delete

How to trigger the onclick event of a marker on a Google Maps V3?

For future Googlers, If you get an error similar below after you trigger click for a polygon

"Uncaught TypeError: Cannot read property 'vertex' of undefined"

then try the code below

google.maps.event.trigger(polygon, "click", {});

Referencing value in a closed Excel workbook using INDIRECT?

In Excel 2016 at least, you can use INDIRECT with a full path reference; the entire reference (including sheet name) needs to be enclosed by ' characters.

So this should work for you:

= INDIRECT("'C:\data\[myExcelFile.xlsm]" & C13 & "'!$A$1")

Note the closing ' in the last string (ie '!$A$1 surrounded by "")

How do I write data to csv file in columns and rows from a list in python?

Have a go with these code:

>>> import pyexcel as pe
>>> sheet = pe.Sheet(data)
>>> data=[[1, 2], [2, 3], [4, 5]]
>>> sheet
Sheet Name: pyexcel
+---+---+
| 1 | 2 |
+---+---+
| 2 | 3 |
+---+---+
| 4 | 5 |
+---+---+
>>> sheet.save_as("one.csv")
>>> b = [[126, 125, 123, 122, 123, 125, 128, 127, 128, 129, 130, 130, 128, 126, 124, 126, 126, 128, 129, 130, 130, 130, 130, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 134, 134, 134, 134, 134, 134, 134, 134, 133, 134, 135, 134, 133, 133, 134, 135, 136], [135, 135, 136, 137, 137, 136, 134, 135, 135, 135, 134, 134, 133, 133, 133, 134, 134, 134, 133, 133, 132, 132, 132, 135, 135, 133, 133, 133, 133, 135, 135, 131, 135, 136, 134, 133, 136, 137, 136, 133, 134, 135, 136, 136, 135, 134, 133, 133, 134, 135, 136, 136, 136, 135, 134, 135, 138, 138, 135, 135, 138, 138, 135, 139], [137, 135, 136, 138, 139, 137, 135, 142, 139, 137, 139, 138, 136, 137, 141, 138, 138, 139, 139, 139, 139, 138, 138, 138, 138, 137, 137, 137, 137, 138, 138, 136, 137, 137, 137, 137, 137, 137, 138, 148, 144, 140, 138, 137, 138, 138, 138, 137, 137, 137, 137, 137, 138, 139, 140, 141, 141, 141, 141, 141, 141, 141, 141, 141], [141, 141, 141, 141, 141, 141, 141, 139, 139, 139, 140, 140, 141, 141, 141, 140, 140, 140, 140, 140, 141, 142, 143, 138, 138, 138, 139, 139, 140, 140, 140, 141, 140, 139, 139, 141, 141, 140, 139, 145, 137, 137, 145, 145, 137, 137, 144, 141, 139, 146, 134, 145, 140, 149, 144, 145, 142, 140, 141, 144, 145, 142, 139, 140]]
>>> s2 = pe.Sheet(b)
>>> s2
Sheet Name: pyexcel
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 126 | 125 | 123 | 122 | 123 | 125 | 128 | 127 | 128 | 129 | 130 | 130 | 128 | 126 | 124 | 126 | 126 | 128 | 129 | 130 | 130 | 130 | 130 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 134 | 134 | 134 | 134 | 134 | 134 | 134 | 134 | 133 | 134 | 135 | 134 | 133 | 133 | 134 | 135 | 136 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 135 | 135 | 136 | 137 | 137 | 136 | 134 | 135 | 135 | 135 | 134 | 134 | 133 | 133 | 133 | 134 | 134 | 134 | 133 | 133 | 132 | 132 | 132 | 135 | 135 | 133 | 133 | 133 | 133 | 135 | 135 | 131 | 135 | 136 | 134 | 133 | 136 | 137 | 136 | 133 | 134 | 135 | 136 | 136 | 135 | 134 | 133 | 133 | 134 | 135 | 136 | 136 | 136 | 135 | 134 | 135 | 138 | 138 | 135 | 135 | 138 | 138 | 135 | 139 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 137 | 135 | 136 | 138 | 139 | 137 | 135 | 142 | 139 | 137 | 139 | 138 | 136 | 137 | 141 | 138 | 138 | 139 | 139 | 139 | 139 | 138 | 138 | 138 | 138 | 137 | 137 | 137 | 137 | 138 | 138 | 136 | 137 | 137 | 137 | 137 | 137 | 137 | 138 | 148 | 144 | 140 | 138 | 137 | 138 | 138 | 138 | 137 | 137 | 137 | 137 | 137 | 138 | 139 | 140 | 141 | 141 | 141 | 141 | 141 | 141 | 141 | 141 | 141 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 141 | 141 | 141 | 141 | 141 | 141 | 141 | 139 | 139 | 139 | 140 | 140 | 141 | 141 | 141 | 140 | 140 | 140 | 140 | 140 | 141 | 142 | 143 | 138 | 138 | 138 | 139 | 139 | 140 | 140 | 140 | 141 | 140 | 139 | 139 | 141 | 141 | 140 | 139 | 145 | 137 | 137 | 145 | 145 | 137 | 137 | 144 | 141 | 139 | 146 | 134 | 145 | 140 | 149 | 144 | 145 | 142 | 140 | 141 | 144 | 145 | 142 | 139 | 140 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
>>> s2[0,0]
126
>>> s2.save_as("two.csv")

HttpURLConnection timeout settings

HttpURLConnection has a setConnectTimeout method.

Just set the timeout to 5000 milliseconds, and then catch java.net.SocketTimeoutException

Your code should look something like this:


try {
   HttpURLConnection.setFollowRedirects(false);
   HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
   con.setRequestMethod("HEAD");

   con.setConnectTimeout(5000); //set timeout to 5 seconds

   return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (java.net.SocketTimeoutException e) {
   return false;
} catch (java.io.IOException e) {
   return false;
}


How to set True as default value for BooleanField on Django?

from django.db import models

class Foo(models.Model):
    any_field = models.BooleanField(default=True)

node.js hash string?

I use blueimp-md5 which is "Compatible with server-side environments like Node.js, module loaders like RequireJS, Browserify or webpack and all web browsers."

Use it like this:

var md5 = require("blueimp-md5");

var myHashedString = createHash('GreensterRox');

createHash(myString){
    return md5(myString);
}

If passing hashed values around in the open it's always a good idea to salt them so that it is harder for people to recreate them:

createHash(myString){
    var salt = 'HnasBzbxH9';
    return md5(myString+salt);
}

Should you commit .gitignore into the Git repos?

Committing .gitignore can be very useful but you want to make sure you don't modify it too much thereafter especially if you regularly switch between branches. If you do you might get cases where files are ignored in a branch and not in the other, forcing you to go manually delete or rename files in your work directory because a checkout failed as it would overwrite a non-tracked file.

Therefore yes, do commit your .gitignore, but not before you are reasonably sure it won't change that much thereafter.

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname

An example of retrieving data from a table having columns column1, column2 ,column3 column4, cloumn1 and 2 hold int values and column 3 and 4 hold varchar(10)

import java.sql.*; 
// need to import this as the STEP 1. Has the classes that you mentioned  
public class JDBCexample {
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; 
    static final String DB_URL = "jdbc:mysql://LocalHost:3306/databaseNameHere"; 
    // DON'T PUT ANY SPACES IN BETWEEN and give the name of the database (case insensitive) 

    // database credentials
    static final String USER = "root";
    // usually when you install MySQL, it logs in as root 
    static final String PASS = "";
    // and the default password is blank

    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;

        try {
    // registering the driver__STEP 2
            Class.forName("com.mysql.jdbc.Driver"); 
    // returns a Class object of com.mysql.jdbc.Driver
    // (forName(""); initializes the class passed to it as String) i.e initializing the
    // "suitable" driver
            System.out.println("connecting to the database");
    // opening a connection__STEP 3
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
    // executing a query__STEP 4 
            System.out.println("creating a statement..");
            stmt = conn.createStatement();
    // creating an object to create statements in SQL
            String sql;
            sql = "SELECT column1, cloumn2, column3, column4 from jdbcTest;";
    // this is what you would have typed in CLI for MySQL
            ResultSet rs = stmt.executeQuery(sql);
    // executing the query__STEP 5 (and retrieving the results in an object of ResultSet)
    // extracting data from result set
            while(rs.next()){
    // retrieve by column name
                int value1 = rs.getInt("column1");
                int value2 = rs.getInt("column2");
                String value3 = rs.getString("column3");
                String value4 = rs.getString("columnm4");
    // displaying values:
                System.out.println("column1 "+ value1);
                System.out.println("column2 "+ value2);
                System.out.println("column3 "+ value3);
                System.out.println("column4 "+ value4);

            }
    // cleaning up__STEP 6
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException e) {
    //  handle sql exception
            e.printStackTrace();
        }catch (Exception e) {
    // TODO: handle exception for class.forName
            e.printStackTrace();
        }finally{  
    //closing the resources..STEP 7
            try {
                if (stmt != null)
                    stmt.close();
            } catch (SQLException e2) {
                e2.printStackTrace();
            }try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e2) {
                e2.printStackTrace();
            }
        }
        System.out.println("good bye");
    }
}

How to Set OnClick attribute with value containing function in ie8?

You could also set onclick to call your function like this:

foo.onclick = function() { callYourJSFunction(arg1, arg2); };

This way, you can pass arguments too. .....

Practical uses of different data structures

The excellent book "Algorithm Design Manual" by Skienna contains a huge repository of Algorithms and Data structure.

For tons of problems, data structures and algorithm are described, compared, and discusses the practical usage. The author also provides references to implementations and the original research papers.

The book is great to have it on your desk if you search the best data structure for your problem to solve. It is also very helpful for interview preparation.

Another great resource is the NIST Dictionary of Data structures and algorithms.

SQL Server "AFTER INSERT" trigger doesn't see the just-inserted row

I think you can use CHECK constraint - it is exactly what it was invented for.

ALTER TABLE someTable 
ADD CONSTRAINT someField_check CHECK (ISNUMERIC(someField) = 1) ;

My previous answer (also right by may be a bit overkill):

I think the right way is to use INSTEAD OF trigger to prevent the wrong data from being inserted (rather than deleting it post-factum)

How to measure elapsed time

When the game starts:

long tStart = System.currentTimeMillis();

When the game ends:

long tEnd = System.currentTimeMillis();
long tDelta = tEnd - tStart;
double elapsedSeconds = tDelta / 1000.0;

What is the difference between RTP or RTSP in a streaming server?

I hear your pain. I'm going through this right now (years later). From what I've learned, you can think of RTSP as a "VCR controller", the protocol allows you to specify which streams (presentations) you want to play, it will then send you a description of the media, and then you can use RTSP to play, stop, pause, and record the remote stream. The media itself goes over RTP. RTSP is normally implemented over a different socket or communication layer. Although it is simply a protocol, most often it's implemented by a server over a socket. For live streams, the RTSP stream you request is simply a name of a stream. It doesn't need to refer to a file on the server, the server's RTSP implementation can parse that stream, put together a live graph, and then provide the SDP (description) for that stream name. But, this is of course specific to the way the RTSP server has been implemented. For "live" streams, it's probably simpler to just use RTP, but you'll need a way to transfer the SDP from the RTP server to the client that wants to play that stream.

MySQL Multiple Where Clause

select unique red24.image_id from 
( 
    select image_id from `list` where style_id = 24 and style_value = 'red' 
) red24
inner join 
( 
    select image_id from `list` where style_id = 25 and style_value = 'big' 
) big25
on red24.image_id = big25.image_id
inner join 
( 
    select image_id from `list` where style_id = 27 and style_value = 'round' 
) round27
on red24.image_id = round27.image_id

How to make Excel VBA variables available to multiple macros?

Declare them outside the subroutines, like this:

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

Alternately, you can pass variables between subroutines:

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

Or use Functions to return values:

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

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

A Note About User Forms

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

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

enter image description here

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

enter image description here

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

Different ways of loading a file as an InputStream

Use MyClass.class.getClassLoader().getResourceAsStream(path) to load resource associated with your code. Use MyClass.class.getResourceAsStream(path) as a shortcut, and for resources packaged within your class' package.

Use Thread.currentThread().getContextClassLoader().getResourceAsStream(path) to get resources that are part of client code, not tightly bounds to the calling code. You should be careful with this as the thread context class loader could be pointing at anything.

how to make jni.h be found?

I don't know if this applies in this case, but sometimes the file got deleted for unknown reasons, copying it again into the respective folder should resolve the problem.

Using a PHP variable in a text input value = statement

Solution

You are missing an echo. Each time that you want to show the value of a variable to HTML you need to echo it.

<input type="text" name="idtest" value="<?php echo $idtest; ?>" >

Note: Depending on the value, your echo is the function you use to escape it like htmlspecialchars.

How to load GIF image in Swift?

Load GIF image Swift :

## Reference.

#1 : Copy the swift file from This Link :

#2 : Load GIF image Using Name

    let jeremyGif = UIImage.gifImageWithName("funny")
    let imageView = UIImageView(image: jeremyGif)
    imageView.frame = CGRect(x: 20.0, y: 50.0, width: self.view.frame.size.width - 40, height: 150.0)
    view.addSubview(imageView)

#3 : Load GIF image Using Data

    let imageData = try? Data(contentsOf: Bundle.main.url(forResource: "play", withExtension: "gif")!)
    let advTimeGif = UIImage.gifImageWithData(imageData!)
    let imageView2 = UIImageView(image: advTimeGif)
    imageView2.frame = CGRect(x: 20.0, y: 220.0, width: 
    self.view.frame.size.width - 40, height: 150.0)
    view.addSubview(imageView2)

#4 : Load GIF image Using URL

    let gifURL : String = "http://www.gifbin.com/bin/4802swswsw04.gif"
    let imageURL = UIImage.gifImageWithURL(gifURL)
    let imageView3 = UIImageView(image: imageURL)
    imageView3.frame = CGRect(x: 20.0, y: 390.0, width: self.view.frame.size.width - 40, height: 150.0)
    view.addSubview(imageView3)

Download Demo Code

OUTPUT :

iPhone 8 / iOS 11 / xCode 9

enter image description here

What's the difference between 'int?' and 'int' in C#?

Int cannot accept null but if developer are using int? then you store null in int like int i = null; // not accept int? i = null; // its working mostly use for pagination in MVC Pagelist

virtualenvwrapper and Python 3

This post on the bitbucket issue tracker of virtualenvwrapper may be of interest. It is mentioned there that most of virtualenvwrapper's functions work with the venv virtual environments in Python 3.3.

Xcode 'CodeSign error: code signing is required'

Have you updated the firmware version of the iPhone you are testing on?

ORACLE convert number to string

This should solve your problem:

select replace(to_char(a, '90D90'),'.00','')
from
(
select 50 a from dual
union
select 50.57 from dual
union
select 5.57 from dual
union
select 0.35 from dual
union
select 0.4 from dual
);

Give a look also as this SQL Fiddle for test.

How To Launch Git Bash from DOS Command Line?

I prefer to use git-bash.exe instead of sh.exe.

start "" "%ProgramFiles%\Git\git-bash.exe" -c "tail -f /c/Windows/win.ini"

You can stop closing the window when call /usr/bin/bash --login -i in the end;

start "" "%ProgramFiles%\Git\git-bash.exe" -c "echo 1 && echo 2 && /usr/bin/bash --login -i"

Note: I'm not sure this is a good way :)

Bootstrap dropdown menu not working (not dropping down when clicked)

Adding this script to my code fixed the dropdown menu.

<script>
    $(document).ready(function () {
        $('.dropdown-toggle').dropdown();
    });
</script>

Any tools to generate an XSD schema from an XML instance document?

the Microsoft XSD inference tool is a good, free solution. Many XML editing tools, such as XmlSpy (mentioned by @Garth Gilmour) or OxygenXML Editor also have that feature. They're rather expensive, though. BizTalk Server also has an XSD inferring tool as well.

edit: I just discovered the .net XmlSchemaInference class, so if you're using .net you should consider that

Present and dismiss modal view controller

Swift

self.dismissViewControllerAnimated(true, completion: nil)

How do I make a WPF TextBlock show my text on multiple lines?

Use Linebreak:

<TextBlock>
        <Run Text="Line1"/>
        <LineBreak/>
        <Run Text="Line2" FontStyle="Italic" FontSize="9"/>
        <LineBreak/>
        <Run Text="Line3"/>
    </TextBlock>

Refer this: https://social.msdn.microsoft.com/Forums/vstudio/en-US/51a3ffe4-ec82-404a-9a99-6672f2a6842b/how-to-give-multiline-in-textblock?forum=wpf

Thanks,

RDV

Apache and IIS side by side (both listening to port 80) on windows2003

I see this is quite an old post, but came across this looking for an answer for this problem. After reading some of the answers they seem very long winded, so after about 5 mins I managed to solve the problem very simply as follows:

httpd.conf for Apache leave the listen port as 80 and 'Server Name' as FQDN/IP :80.

Now for IIS go to Administrative Services > IIS Manager > 'Sites' in the Left hand nav drop down > in the right window select the top line (default web site) then bindings on the right.

Now select http > edit and change to 81 and enter your local IP for the server/pc and in domain enter either your FQDN (www.domain.com) or external IP close.

Restart both servers ensure your ports are open on both router and firewall, done.

This sounds long winded but literally took 5 mins of playing about. works perfectly.

System: Windows 8, IIS 8, Apache 2.2

What is attr_accessor in Ruby?

To summarize an attribute accessor aka attr_accessor gives you two free methods.

Like in Java they get called getters and setters.

Many answers have shown good examples so I'm just going to be brief.

#the_attribute

and

#the_attribute=

In the old ruby docs a hash tag # means a method. It could also include a class name prefix... MyClass#my_method

Remove numbers from string sql server

This one works for me

CREATE Function [dbo].[RemoveNumericCharacters](@Temp VarChar(1000))
Returns VarChar(1000)
AS
Begin

    Declare @NumRange as varchar(50) = '%[0-9]%'
    While PatIndex(@NumRange, @Temp) > 0
        Set @Temp = Stuff(@Temp, PatIndex(@NumRange, @Temp), 1, '')

    Return @Temp
End

and you can use it like so

SELECT dbo.[RemoveNumericCharacters](Name) FROM TARGET_TABLE

How to import a single table in to mysql database using command line

Linux :

In command line

 mysql -u username -p  databasename  < path/example.sql

put your table in example.sql

Import / Export for single table:

  1. Export table schema

    mysqldump -u username -p databasename tableName > path/example.sql
    

    This will create a file named example.sql at the path mentioned and write the create table sql command to create table tableName.

  2. Import data into table

    mysql -u username -p databasename < path/example.sql
    

    This command needs an sql file containing data in form of insert statements for table tableName. All the insert statements will be executed and the data will be loaded.

convert string into array of integers

A quick one for modern browsers:

'14 2'.split(' ').map(Number);

// [14, 2]`

how to import csv data into django models

For django 1.8 that im using,

I made a command that you can create objects dynamically in the future, so you can just put the file path of the csv, the model name and the app name of the relevant django application, and it will populate the relevant model without specified the field names. so if we take for example the next csv:

field1,field2,field3
value1,value2,value3
value11,value22,value33

it will create the objects [{field1:value1,field2:value2,field3:value3}, {field1:value11,field2:value22,field3:value33}] for the model name you will enter to the command.

the command code:

from django.core.management.base import BaseCommand
from django.db.models.loading import get_model
import csv


class Command(BaseCommand):
    help = 'Creating model objects according the file path specified'

    def add_arguments(self, parser):
        parser.add_argument('--path', type=str, help="file path")
        parser.add_argument('--model_name', type=str, help="model name")
        parser.add_argument('--app_name', type=str, help="django app name that the model is connected to")

    def handle(self, *args, **options):
        file_path = options['path']
        _model = get_model(options['app_name'], options['model_name'])
        with open(file_path, 'rb') as csv_file:
            reader = csv.reader(csv_file, delimiter=',', quotechar='|')
            header = reader.next()
            for row in reader:
                _object_dict = {key: value for key, value in zip(header, row)}
                _model.objects.create(**_object_dict)

note that maybe in later versions

from django.db.models.loading import get_model

is deprecated and need to be change to

from django.apps.apps import get_model

How can I pair socks from a pile efficiently?

My solution does not exactly correspond to your requirements, as it formally requires O(n) "extra" space. However, considering my conditions it is very efficient in my practical application. Thus I think it should be interesting.

Combine with Other Task

The special condition in my case is that I don't use drying machine, just hang my cloths on an ordinary cloth dryer. Hanging cloths requires O(n) operations (by the way, I always consider bin packing problem here) and the problem by its nature requires the linear "extra" space. When I take a new sock from the bucket I to try hang it next to its pair if the pair is already hung. If its a sock from a new pair I leave some space next to it.

Oracle Machine is Better ;-)

It obviously requires some extra work to check if there is the matching sock already hanging somewhere and it would render solution O(n^2) with coefficient about 1/2 for a computer. But in this case the "human factor" is actually an advantage -- I usually can very quickly (almost O(1)) identify the matching sock if it was already hung (probably some imperceptible in-brain caching is involved) -- consider it a kind of limited "oracle" as in Oracle Machine ;-) We, the humans have these advantages over digital machines in some cases ;-)

Have it Almost O(n)!

Thus connecting the problem of pairing socks with the problem of hanging cloths I get O(n) "extra space" for free, and have a solution that is about O(n) in time, requires just a little more work than simple hanging cloths and allows to immediately access complete pair of socks even in a very bad Monday morning... ;-)

How to run wget inside Ubuntu Docker image?

If you're running ubuntu container directly without a local Dockerfile you can ssh into the container and enable root control by entering su then apt-get install -y wget

Tools to get a pictorial function call graph of code

You can check out my bash-based C call tree generator here. It lets you specify one or more C functions for which you want caller and/or called information, or you can specify a set of functions and determine the reachability graph of function calls that connects them... I.e. tell me all the ways main(), foo(), and bar() are connected. It uses graphviz/dot for a graphing engine.

How can I add an empty directory to a Git repository?

I've been facing the issue with empty directories, too. The problem with using placeholder files is that you need to create them, and delete them, if they are not necessary anymore (because later on there were added sub-directories or files. With big source trees managing these placeholder files can be cumbersome and error prone.

This is why I decided to write an open source tool which can manage the creation/deletion of such placeholder files automatically. It is written for .NET platform and runs under Mono (.NET for Linux) and Windows.

Just have a look at: http://code.google.com/p/markemptydirs

How to create an 2D ArrayList in java?

The best way is to use a List within a List:

List<List<String>> listOfLists = new ArrayList<List<String>>();  

Operator overloading on class templates

You must specify that the friend is a template function:

MyClass<T>& operator+=<>(const MyClass<T>& classObj);

See this C++ FAQ Lite answer for details.

Replace last occurrence of a string in a string

A short version:

$NewString = substr_replace($String,$Replacement,strrpos($String,$Replace),strlen($Replace));

Asp.net 4.0 has not been registered

For those getting this error in after installing .NET Framework 4.6 - Read and install one of these hotfixes to resolve the issue.

Adding Google Translate to a web site

{{-- Google Language Translator  START --}}
<style>
.google-translate {
    display: inline-block;
    vertical-align: top;
    padding-top: 15px;
}

.goog-logo-link {
    display: none !important;
}

.goog-te-gadget {
    color: transparent !important;
}

#google_translate_element {
    display: none;
}

.goog-te-banner-frame.skiptranslate {
    display: none !important;
}

body {
    top: 0px !important;
}

</style>

<script src="{{asset('js/translate-google.js')}}"></script>



<script type="text/javascript">
function googleTranslateElementInit2(){
    new google.translate.TranslateElement({
                    pageLanguage:'en',
                    includedLanguages: 'en,es',
        // https://ctrlq.org/code/19899-google-translate-languages
        // includedLanguages: 'en,it,la,fr',
        // layout:     google.translate.TranslateElement.InlineLayout.SIMPLE,
        autoDisplay:true
    },'google_translate_element2');
    var a = document.querySelector("#google_translate_element select");
    // console.log(a);

    if(a){
        a.selectedIndex=1;
        a.dispatchEvent(new Event('change'));
    }
}
</script>

<ul class="navbar-nav my-lg-0 m-r-10">
<li>
    <div class="google-translate">
        <div id="google_translate_element2"></div>
    </div>
</li>

{{-- Google Language Translator ENDS --}}

// translate-google.js
(function () {
var gtConstEvalStartTime = new Date();

function d(b) {
    var a = document.getElementsByTagName("head")[0];
    a || (a = document.body.parentNode.appendChild(document.createElement("head")));
    a.appendChild(b)
}

function _loadJs(b) {
    // console.log(b);
    var a = document.createElement("script");
    a.type = "text/javascript";
    a.charset = "UTF-8";
    a.src = b;
    d(a)
}

function _loadCss(b) {
    var a = document.createElement("link");
    a.type = "text/css";
    a.rel = "stylesheet";
    a.charset = "UTF-8";
    a.href = b;
    d(a)
}

function _isNS(b) {
    b = b.split(".");
    for (var a = window, c = 0; c < b.length; ++c)
        if (!(a = a[b[c]])) return !1;
    return !0
}

function _setupNS(b) {
    b = b.split(".");
    for (var a = window, c = 0; c < b.length; ++c) a.hasOwnProperty ? a.hasOwnProperty(b[c]) ? a = a[b[c]] : a = a[b[c]] = {} : a = a[b[c]] || (a[b[c]] = {});
    return a
}
window.addEventListener && "undefined" == typeof document.readyState && window.addEventListener("DOMContentLoaded", function () {
    document.readyState = "complete"
}, !1);
if (_isNS('google.translate.Element')) {
    return
}(function () {
    var c = _setupNS('google.translate._const');
    c._cest = gtConstEvalStartTime;
    gtConstEvalStartTime = undefined;
    c._cl = 'en';
    c._cuc = 'googleTranslateElementInit2';
    c._cac = '';
    c._cam = '';
    c._ctkk = eval('((function(){var a\x3d3002255536;var b\x3d-2533142796;return 425386+\x27.\x27+(a+b)})())');
    var h = 'translate.googleapis.com';
    var s = (true ? 'https' : window.location.protocol == 'https:' ? 'https' : 'http') + '://';
    var b = s + h;
    c._pah = h;
    c._pas = s;
    c._pbi = b + '/translate_static/img/te_bk.gif';
    c._pci = b + '/translate_static/img/te_ctrl3.gif';
    c._pli = b + '/translate_static/img/loading.gif';
    c._plla = h + '/translate_a/l';
    c._pmi = b + '/translate_static/img/mini_google.png';
    c._ps = b + '/translate_static/css/translateelement.css';
    c._puh = 'translate.google.com';
    _loadCss(c._ps);
    _loadJs(b + '/translate_static/js/element/main.js');
})();
})();

Define global constants

You can make a class for your global variable and then export this class like this:

export class CONSTANT {
    public static message2 = [
        { "NAME_REQUIRED": "Name is required" }
    ]

    public static message = {
        "NAME_REQUIRED": "Name is required",
    }
}

After creating and exporting your CONSTANT class, you should import this class in that class where you want to use, like this:

import { Component, OnInit                       } from '@angular/core';
import { CONSTANT                                } from '../../constants/dash-constant';


@Component({
  selector   : 'team-component',
  templateUrl: `../app/modules/dashboard/dashComponents/teamComponents/team.component.html`,
})

export class TeamComponent implements OnInit {
  constructor() {
    console.log(CONSTANT.message2[0].NAME_REQUIRED);
    console.log(CONSTANT.message.NAME_REQUIRED);
  }

  ngOnInit() {
    console.log("oninit");
    console.log(CONSTANT.message2[0].NAME_REQUIRED);
    console.log(CONSTANT.message.NAME_REQUIRED);
  }
}

You can use this either in constructor or ngOnInit(){}, or in any predefine methods.

How to split a string by spaces in a Windows batch file?

see HELP FOR and see the examples

or quick try this

 for /F %%a in ("AAA BBB CCC DDD EEE FFF") do echo %%c

My docker container has no internet

I do not know what I am doing but that worked for me :

OTHER_BRIDGE=br-xxxxx # this is the other random docker bridge (`ip addr` to find)    
service docker stop

ip link set dev $OTHER_BRIDGE down
ip link set dev docker0 down
ip link delete $OTHER_BRIDGE type bridge
ip link delete docker0 type bridge
service docker start && service docker stop

iptables -t nat -A POSTROUTING ! -o docker0 -s 172.17.0.0/16 -j MASQUERADE
iptables -t nat -A POSTROUTING ! -o docker0 -s 172.18.0.0/16 -j MASQUERADE

service docker start

Adding one day to a date

$date = new DateTime('2000-12-31');

$date->modify('+1 day');
echo $date->format('Y-m-d') . "\n";

C++ program converts fahrenheit to celsius

Fahrenheit to celsius would be (Fahrenheit - 32) * 5 / 9

Variable's memory size in Python

Use sys.getsizeof to get the size of an object, in bytes.

>>> from sys import getsizeof
>>> a = 42
>>> getsizeof(a)
12
>>> a = 2**1000
>>> getsizeof(a)
146
>>>

Note that the size and layout of an object is purely implementation-specific. CPython, for example, may use totally different internal data structures than IronPython. So the size of an object may vary from implementation to implementation.

Disable Logback in SpringBoot

Find spring-boot-starter-test in your pom.xml and modify it as follows:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <exclusions>
            <exclusion>
                <artifactId>commons-logging</artifactId>
                <groupId>commons-logging</groupId>
            </exclusion>
        </exclusions>
        <scope>test</scope>
    </dependency>

It fixed error like:

_Caused by: java.lang.IllegalArgumentException:_ **LoggerFactory** is not a **Logback LoggerContext** but *Logback* is on the classpath.

Either remove **Logback** or the competing implementation

(_class org.apache.logging.slf4j.Log4jLoggerFactory_
loaded from file: 

**${M2_HOME}/repository/org/apache/logging/log4j/log4j-slf4j-impl/2.6.2/log4j-slf4j-impl-2.6.2.jar**).

If you are using WebLogic you will need to add **'org.slf4j'** to prefer-application-packages in WEB-INF/weblogic.xml: **org.apache.logging.slf4j.Log4jLoggerFactory**

How does the 'binding' attribute work in JSF? When and how should it be used?

How does it work?

When a JSF view (Facelets/JSP file) get built/restored, a JSF component tree will be produced. At that moment, the view build time, all binding attributes are evaluated (along with id attribtues and taghandlers like JSTL). When the JSF component needs to be created before being added to the component tree, JSF will check if the binding attribute returns a precreated component (i.e. non-null) and if so, then use it. If it's not precreated, then JSF will autocreate the component "the usual way" and invoke the setter behind binding attribute with the autocreated component instance as argument.

In effects, it binds a reference of the component instance in the component tree to a scoped variable. This information is in no way visible in the generated HTML representation of the component itself. This information is in no means relevant to the generated HTML output anyway. When the form is submitted and the view is restored, the JSF component tree is just rebuilt from scratch and all binding attributes will just be re-evaluated like described in above paragraph. After the component tree is recreated, JSF will restore the JSF view state into the component tree.

Component instances are request scoped!

Important to know and understand is that the concrete component instances are effectively request scoped. They're newly created on every request and their properties are filled with values from JSF view state during restore view phase. So, if you bind the component to a property of a backing bean, then the backing bean should absolutely not be in a broader scope than the request scope. See also JSF 2.0 specitication chapter 3.1.5:

3.1.5 Component Bindings

...

Component bindings are often used in conjunction with JavaBeans that are dynamically instantiated via the Managed Bean Creation facility (see Section 5.8.1 “VariableResolver and the Default VariableResolver”). It is strongly recommend that application developers place managed beans that are pointed at by component binding expressions in “request” scope. This is because placing it in session or application scope would require thread-safety, since UIComponent instances depends on running inside of a single thread. There are also potentially negative impacts on memory management when placing a component binding in “session” scope.

Otherwise, component instances are shared among multiple requests, possibly resulting in "duplicate component ID" errors and "weird" behaviors because validators, converters and listeners declared in the view are re-attached to the existing component instance from previous request(s). The symptoms are clear: they are executed multiple times, one time more with each request within the same scope as the component is been bound to.

And, under heavy load (i.e. when multiple different HTTP requests (threads) access and manipulate the very same component instance at the same time), you may face sooner or later an application crash with e.g. Stuck thread at UIComponent.popComponentFromEL, or Java Threads at 100% CPU utilization using richfaces UIDataAdaptorBase and its internal HashMap, or even some "strange" IndexOutOfBoundsException or ConcurrentModificationException coming straight from JSF implementation source code while JSF is busy saving or restoring the view state (i.e. the stack trace indicates saveState() or restoreState() methods and like).

Using binding on a bean property is bad practice

Regardless, using binding this way, binding a whole component instance to a bean property, even on a request scoped bean, is in JSF 2.x a rather rare use case and generally not the best practice. It indicates a design smell. You normally declare components in the view side and bind their runtime attributes like value, and perhaps others like styleClass, disabled, rendered, etc, to normal bean properties. Then, you just manipulate exactly that bean property you want instead of grabbing the whole component and calling the setter method associated with the attribute.

In cases when a component needs to be "dynamically built" based on a static model, better is to use view build time tags like JSTL, if necessary in a tag file, instead of createComponent(), new SomeComponent(), getChildren().add() and what not. See also How to refactor snippet of old JSP to some JSF equivalent?

Or, if a component needs to be "dynamically rendered" based on a dynamic model, then just use an iterator component (<ui:repeat>, <h:dataTable>, etc). See also How to dynamically add JSF components.

Composite components is a completely different story. It's completely legit to bind components inside a <cc:implementation> to the backing component (i.e. the component identified by <cc:interface componentType>. See also a.o. Split java.util.Date over two h:inputText fields representing hour and minute with f:convertDateTime and How to implement a dynamic list with a JSF 2.0 Composite Component?

Only use binding in local scope

However, sometimes you'd like to know about the state of a different component from inside a particular component, more than often in use cases related to action/value dependent validation. For that, the binding attribute can be used, but not in combination with a bean property. You can just specify an in the local EL scope unique variable name in the binding attribute like so binding="#{foo}" and the component is during render response elsewhere in the same view directly as UIComponent reference available by #{foo}. Here are several related questions where such a solution is been used in the answer:

See also:

Oracle date to string conversion

The data in COL1 is in dd-mon-yy

No it's not. A DATE column does not have any format. It is only converted (implicitely) to that representation by your SQL client when you display it.

If COL1 is really a DATE column using to_date() on it is useless because to_date() converts a string to a DATE.

You only need to_char(), nothing else:

SELECT TO_CHAR(col1, 'mm/dd/yyyy') 
FROM TABLE1

What happens in your case is that calling to_date() converts the DATE into a character value (applying the default NLS format) and then converting that back to a DATE. Due to this double implicit conversion some information is lost on the way.


Edit

So you did make that big mistake to store a DATE in a character column. And that's why you get the problems now.

The best (and to be honest: only sensible) solution is to convert that column to a DATE. Then you can convert the values to any rerpresentation that you want without worrying about implicit data type conversion.

But most probably the answer is "I inherited this model, I have to cope with it" (it always is, apparently no one ever is responsible for choosing the wrong datatype), then you need to use RR instead of YY:

SELECT TO_CHAR(TO_DATE(COL1,'dd-mm-rr'), 'mm/dd/yyyy')
FROM TABLE1

should do the trick. Note that I also changed mon to mm as your example is 27-11-89 which has a number for the month, not an "word" (like NOV)

For more details see the manual: http://docs.oracle.com/cd/B28359_01/server.111/b28286/sql_elements004.htm#SQLRF00215

Access a function variable outside the function without using "global"

You could do something along these lines (which worked in both Python v2.7.17 and v3.8.1 when I tested it/them):

def hi():
    # other code...
    hi.bye = 42  # Create function attribute.
    sigh = 10

hi()
print(hi.bye)  # -> 42

Functions are objects in Python and can have arbitrary attributes assigned to them.

If you're going to be doing this kind of thing often, you could implement something more generic by creating a function decorator that adds a this argument to each call to the decorated function.

This additional argument will give functions a way to reference themselves without needing to explicitly embed (hardcode) their name into the rest of the definition and is similar to the instance argument that class methods automatically receive as their first argument which is usually named self — I picked something different to avoid confusion, but like the self argument, it can be named whatever you wish.

Here's an example of that approach:

def add_this_arg(func):
    def wrapped(*args, **kwargs):
        return func(wrapped, *args, **kwargs)
    return wrapped

@add_this_arg
def hi(this, that):
    # other code...
    this.bye = 2 * that  # Create function attribute.
    sigh = 10

hi(21)
print(hi.bye)  # -> 42

Note

This doesn't work for class methods. Just use the self argument already passed being passed to instead of the method name. You can reference class-level attributes through type(self). See Function's attributes when in a class.

How do I find all files containing specific text on Linux?

To search for the string and output just that line with the search string:

for i in $(find /path/of/target/directory -type f); do grep -i "the string to look for" "$i"; done

e.g.:

for i in $(find /usr/share/applications -type f); \
do grep -i "web browser" "$i"; done

To display filename containing the search string:

for i in $(find /path/of/target/directory -type f); do if grep -i "the string to look for" "$i" > /dev/null; then echo "$i"; fi; done;

e.g.:

for i in $(find /usr/share/applications -type f); \
do if grep -i "web browser" "$i" > /dev/null; then echo "$i"; \
fi; done;

Sending Arguments To Background Worker?

You should always try to use a composite object with concrete types (using composite design pattern) rather than a list of object types. Who would remember what the heck each of those objects is? Think about maintenance of your code later on... Instead, try something like this:

Public (Class or Structure) MyPerson
                public string FirstName { get; set; }
                public string LastName { get; set; }
                public string Address { get; set; }
                public int ZipCode { get; set; }
End Class

And then:

Dim person as new MyPerson With { .FirstName = “Joe”,
                                  .LastName = "Smith”,
                                  ...
                                 }
backgroundWorker1.RunWorkerAsync(person)

and then:

private void backgroundWorker1_DoWork (object sender, DoWorkEventArgs e)
{
        MyPerson person = e.Argument as MyPerson
        string firstname = person.FirstName;
        string lastname = person.LastName;
        int zipcode = person.ZipCode;                                 
}

Comparing arrays for equality in C++

If you are reluctant to change your existing code to std::array, then use a couple of methods instead which takes non-type template arguments :

//Passed arrays store different data types
template <typename T, typename U, int size1, int size2>
bool equal(T (&arr1)[size1], U (&arr2)[size2] ){
    return false;
}

//Passed arrays store SAME data types
template <typename T, int size1, int size2>
bool equal(T (&arr1)[size1], T (&arr2)[size2] ){
    if(size1 == size2) {
        for(int i = 0 ; i < size1; ++i){
            if(arr1[i] != arr2[i]) return false;
        }
        return true;
    }
    return false;
}

Here is the demo. Note that, while calling, we just need to pass the array variables e.g. equal(iar1, iar2) in your case, no need to pass the size of arrays.

sscanf in Python

There is also the parse module.

parse() is designed to be the opposite of format() (the newer string formatting function in Python 2.6 and higher).

>>> from parse import parse
>>> parse('{} fish', '1')
>>> parse('{} fish', '1 fish')
<Result ('1',) {}>
>>> parse('{} fish', '2 fish')
<Result ('2',) {}>
>>> parse('{} fish', 'red fish')
<Result ('red',) {}>
>>> parse('{} fish', 'blue fish')
<Result ('blue',) {}>

Sum rows in data.frame or matrix

I came here hoping to find a way to get the sum across all columns in a data table and run into issues implementing the above solutions. A way to add a column with the sum across all columns uses the cbind function:

cbind(data, total = rowSums(data))

This method adds a total column to the data and avoids the alignment issue yielded when trying to sum across ALL columns using the above solutions (see the post below for a discussion of this issue).

Adding a new column to matrix error

explicit casting from super class to subclass

In order to avoid this kind of ClassCastException, if you have:

class A
class B extends A

You can define a constructor in B that takes an object of A. This way we can do the "cast" e.g.:

public B(A a) {
    super(a.arg1, a.arg2); //arg1 and arg2 must be, at least, protected in class A
    // If B class has more attributes, then you would initilize them here
}

MVC Form not able to post List of objects

Your model is null because the way you're supplying the inputs to your form means the model binder has no way to distinguish between the elements. Right now, this code:

@foreach (var planVM in Model)
{
    @Html.Partial("_partialView", planVM)
}

is not supplying any kind of index to those items. So it would repeatedly generate HTML output like this:

<input type="hidden" name="yourmodelprefix.PlanID" />
<input type="hidden" name="yourmodelprefix.CurrentPlan" />
<input type="checkbox" name="yourmodelprefix.ShouldCompare" />

However, as you're wanting to bind to a collection, you need your form elements to be named with an index, such as:

<input type="hidden" name="yourmodelprefix[0].PlanID" />
<input type="hidden" name="yourmodelprefix[0].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[0].ShouldCompare" />
<input type="hidden" name="yourmodelprefix[1].PlanID" />
<input type="hidden" name="yourmodelprefix[1].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[1].ShouldCompare" />

That index is what enables the model binder to associate the separate pieces of data, allowing it to construct the correct model. So here's what I'd suggest you do to fix it. Rather than looping over your collection, using a partial view, leverage the power of templates instead. Here's the steps you'd need to follow:

  1. Create an EditorTemplates folder inside your view's current folder (e.g. if your view is Home\Index.cshtml, create the folder Home\EditorTemplates).
  2. Create a strongly-typed view in that directory with the name that matches your model. In your case that would be PlanCompareViewModel.cshtml.

Now, everything you have in your partial view wants to go in that template:

@model PlanCompareViewModel
<div>
    @Html.HiddenFor(p => p.PlanID)
    @Html.HiddenFor(p => p.CurrentPlan)
    @Html.CheckBoxFor(p => p.ShouldCompare)
   <input type="submit" value="Compare"/>
</div>

Finally, your parent view is simplified to this:

@model IEnumerable<PlanCompareViewModel>
@using (Html.BeginForm("ComparePlans", "Plans", FormMethod.Post, new { id = "compareForm" }))
{
<div>
    @Html.EditorForModel()
</div>
}

DisplayTemplates and EditorTemplates are smart enough to know when they are handling collections. That means they will automatically generate the correct names, including indices, for your form elements so that you can correctly model bind to a collection.

Specifying colClasses in the read.csv

The colClasses vector must have length equal to the number of imported columns. Supposing the rest of your dataset columns are 5:

colClasses=c("character",rep("numeric",5))

How to get Linux console window width in Python

use

import console
(width, height) = console.getTerminalSize()

print "Your terminal's width is: %d" % width

EDIT: oh, I'm sorry. That's not a python standard lib one, here's the source of console.py (I don't know where it's from).

The module seems to work like that: It checks if termcap is available, when yes. It uses that; if no it checks whether the terminal supports a special ioctl call and that does not work, too, it checks for the environment variables some shells export for that. This will probably work on UNIX only.

def getTerminalSize():
    import os
    env = os.environ
    def ioctl_GWINSZ(fd):
        try:
            import fcntl, termios, struct, os
            cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,
        '1234'))
        except:
            return
        return cr
    cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
    if not cr:
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            cr = ioctl_GWINSZ(fd)
            os.close(fd)
        except:
            pass
    if not cr:
        cr = (env.get('LINES', 25), env.get('COLUMNS', 80))

        ### Use get(key[, default]) instead of a try/catch
        #try:
        #    cr = (env['LINES'], env['COLUMNS'])
        #except:
        #    cr = (25, 80)
    return int(cr[1]), int(cr[0])

Error in eval(expr, envir, enclos) : object not found

I think I got what I was looking for..

data.train <- read.table("Assign2.WineComplete.csv",sep=",",header=T)
fit <- rpart(quality ~ ., method="class",data=data.train)
plot(fit)
text(fit, use.n=TRUE)
summary(fit)

Why do I get "warning longer object length is not a multiple of shorter object length"?

When you perform a boolean comparison between two vectors in R, the "expectation" is that both vectors are of the same length, so that R can compare each corresponding element in turn.

R has a much loved (or hated) feature called recycling, whereby in many circumstances if you try to do something where R would normally expect objects to be of the same length, it will automatically extend, or recycle, the shorter object to force both objects to be of the same length.

If the longer object is a multiple of the shorter, this amounts to simply repeating the shorter object several times. Oftentimes R programmers will take advantage of this to do things more compactly and with less typing.

But if they are not multiples, R will worry that you may have made a mistake, and perhaps didn't mean to perform that comparison, hence the warning.

Explore yourself with the following code:

> x <- 1:3
> y <- c(1,2,4)
> x == y
[1]  TRUE  TRUE FALSE
> y1 <- c(y,y)
> x == y1
[1]  TRUE  TRUE FALSE  TRUE  TRUE FALSE
> y2 <- c(y,2)
> x == y2
[1]  TRUE  TRUE FALSE FALSE
Warning message:
In x == y2 :
  longer object length is not a multiple of shorter object length

Makefile, header dependencies

A slightly modified version of Sophie's answer which allows to output the *.d files to a different folder (I will only paste the interesting part that generates the dependency files):

$(OBJDIR)/%.o: %.cpp
# Generate dependency file
    mkdir -p $(@D:$(OBJDIR)%=$(DEPDIR)%)
    $(CXX) $(CXXFLAGS) $(CPPFLAGS) -MM -MT $@ $< -MF $(@:$(OBJDIR)/%.o=$(DEPDIR)/%.d)
# Generate object file
    mkdir -p $(@D)
    $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $< -o $@

Note that the parameter

-MT $@

is used to ensure that the targets (i.e. the object file names) in the generated *.d files contain the full path to the *.o files and not just the file name.

I don't know why this parameter is NOT needed when using -MMD in combination with -c (as in Sophie's version). In this combination it seems to write the full path of the *.o files into the *.d files. Without this combination, -MMD also writes only the pure file names without any directory components into the *.d files. Maybe somebody knows why -MMD writes the full path when combined with -c. I have not found any hint in the g++ man page.

How do I get length of list of lists in Java?

count of the contained lists in the outmost list

int count = data.size();

lambda to get the count of the contained inner lists

int count = data.stream().collect( summingInt(l -> l.size()) );

Check if string contains a value in array

I came up with this function which works for me, hope this will help somebody

$word_list = 'word1, word2, word3, word4';
$str = 'This string contains word1 in it';

function checkStringAgainstList($str, $word_list)
{
  $word_list = explode(', ', $word_list);
  $str = explode(' ', $str);

  foreach ($str as $word):
    if (in_array(strtolower($word), $word_list)) {
        return TRUE;
    }
  endforeach;

  return false;
}

Also, note that answers with strpos() will return true if the matching word is a part of other word. For example if word list contains 'st' and if your string contains 'street', strpos() will return true

Git merge master into feature branch

Based on this article, you should:

  • create new branch which is based upon new version of master

    git branch -b newmaster

  • merge your old feature branch into new one

    git checkout newmaster

  • resolve conflict on new feature branch

The first two commands can be combined to git checkout -b newmaster.

This way your history stays clear because you don't need back merges. And you don't need to be so super cautious since you don't need to do a Git rebase.

Iterating through a JSON object

Adding another solution (Python 3) - Iterating over json files in a directory and on each file iterating over all objects and printing relevant fields.

See comments in the code.

import os,json

data_path = '/path/to/your/json/files'  

# 1. Iterate over directory
directory = os.fsencode(data_path)
for file in os.listdir(directory):
    filename = os.fsdecode(file)
    # 2. Take only json files
    if filename.endswith(".json"):
        file_full_path=data_path+filename
        # 3. Open json file 
        with open(file_full_path, encoding='utf-8', errors='ignore') as json_data:
            data_in_file = json.load(json_data, strict=False)
            # 4. Iterate over objects and print relevant fields
            for json_object in data_in_file:
                print("ttl: %s, desc: %s" % (json_object['title'],json_object['description']) )

How to create a function in SQL Server

How about this?

CREATE FUNCTION dbo.StripWWWandCom (@input VARCHAR(250))
RETURNS VARCHAR(250)
AS BEGIN
    DECLARE @Work VARCHAR(250)

    SET @Work = @Input

    SET @Work = REPLACE(@Work, 'www.', '')
    SET @Work = REPLACE(@Work, '.com', '')

    RETURN @work
END

and then use:

SELECT ID, dbo.StripWWWandCom (WebsiteName)
FROM dbo.YourTable .....

Of course, this is severely limited in that it will only strip www. at the beginning and .com at the end - nothing else (so it won't work on other host machine names like smtp.yahoo.com and other internet domains such as .org, .edu, .de and etc.)

nodejs send html file to client

Try your code like this:

var app = express();
app.get('/test', function(req, res) {
    res.sendFile('views/test.html', {root: __dirname })
});
  1. Use res.sendFile instead of reading the file manually so express can handle setting the content-type properly for you.

  2. You don't need the app.engine line, as that is handled internally by express.

Typescript: How to extend two classes?

I would suggest using the new mixins approach described there: https://blogs.msdn.microsoft.com/typescript/2017/02/22/announcing-typescript-2-2/

This approach is better, than the "applyMixins" approach described by Fenton, because the autocompiler would help you and show all the methods / properties from the both base and 2nd inheritance classes.

This approach might be checked on the TS Playground site.

Here is the implementation:

class MainClass {
    testMainClass() {
        alert("testMainClass");
    }
}

const addSecondInheritance = (BaseClass: { new(...args) }) => {
    return class extends BaseClass {
        testSecondInheritance() {
            alert("testSecondInheritance");
        }
    }
}

// Prepare the new class, which "inherits" 2 classes (MainClass and the cass declared in the addSecondInheritance method)
const SecondInheritanceClass = addSecondInheritance(MainClass);
// Create object from the new prepared class
const secondInheritanceObj = new SecondInheritanceClass();
secondInheritanceObj.testMainClass();
secondInheritanceObj.testSecondInheritance();

Scrolling an iframe with JavaScript?

Inspired by Nelson's and Chris' comments, I've found a way to workaround the same origin policy with a div and an iframe:

HTML:

<div id='div_iframe'><iframe id='frame' src='...'></iframe></div>

CSS:

#div_iframe {
  border-style: inset;
  border-color: grey;
  overflow: scroll;
  height: 500px;
  width: 90%
}

#frame {
  width: 100%;
  height: 1000%;   /* 10x the div height to embrace the whole page */
}

Now suppose I want to skip the first 438 (vertical) pixels of the iframe page, by scrolling to that position.

JS solution:

document.getElementById('div_iframe').scrollTop = 438

JQuery solution:

$('#div_iframe').scrollTop(438)

CSS solution:

#frame { margin-top: -438px }

(Each solution alone is enough, and the effect of the CSS one is a little different since you can't scroll up to see the top of the iframed page.)

How to inject Javascript in WebBrowser control?

Here is the easiest way that I found after working on this:

string javascript = "alert('Hello');";
// or any combination of your JavaScript commands
// (including function calls, variables... etc)

// WebBrowser webBrowser1 is what you are using for your web browser
webBrowser1.Document.InvokeScript("eval", new object[] { javascript });

What global JavaScript function eval(str) does is parses and executes whatever is written in str. Check w3schools ref here.

How to access data/data folder in Android device?

To backup from Android to Desktop

Open command line cmd and run this: adb backup -f C:\Intel\xxx.ab -noapk your.app.package. Do not enter password and click on Backup my data. Make sure not to save on drive C root. You may be denied. This is why I saved on C:\Intel.

To extract the *.ab file

  1. Go here and download: https://sourceforge.net/projects/adbextractor/
  2. Extract the downloaded file and navigate to folder where you extracted.
  3. run this with your own file names: java -jar abe.jar unpack c:\Intel\xxx.ab c:\Intel\xxx.tar

How to generate a HTML page dynamically using PHP?

I suggest you to use URL rewrite mod is enough for your problem,I have the same problem but using URL rewrite mod and getting good SEO response. I can give you a small example. Example is that you consider WordPress , here the data is stored in database but using URL rewrite mod many WordPress websites getting good responses from Google and got rank also.

Example: wordpress url with out url rewrite mod -- domain.com/?p=123 after url rewrite mode -- domain.com/{title of article} like domain.com/seo-url-rewrite-mod

i think you have understood what i want to say you

How do I filter date range in DataTables?

Here is my solution, there is no way to use momemt.js.Here is DataTable with Two DatePickers for DateRange (To and From) Filter.

$.fn.dataTable.ext.search.push(
  function (settings, data, dataIndex) {
    var min = $('#min').datepicker("getDate");
    var max = $('#max').datepicker("getDate");
    var startDate = new Date(data[4]);
    if (min == null && max == null) { return true; }
    if (min == null && startDate <= max) { return true; }
    if (max == null && startDate >= min) { return true; }
    if (startDate <= max && startDate >= min) { return true; }
    return false;
  }
);
  

    

How to see the actual Oracle SQL statement that is being executed

-- i use something like this, with concepts and some code stolen from asktom.
-- suggestions for improvements are welcome

WITH
sess AS
(
SELECT *
FROM V$SESSION
WHERE USERNAME = USER
ORDER BY SID
)
SELECT si.SID,
si.LOCKWAIT,
si.OSUSER,
si.PROGRAM,
si.LOGON_TIME,
si.STATUS,
(
SELECT ROUND(USED_UBLK*8/1024,1)
FROM V$TRANSACTION,
sess
WHERE sess.TADDR = V$TRANSACTION.ADDR
AND sess.SID = si.SID

) rollback_remaining,

(
SELECT (MAX(DECODE(PIECE, 0,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 1,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 2,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 3,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 4,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 5,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 6,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 7,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 8,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 9,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 10,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 11,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 12,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 13,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 14,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 15,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 16,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 17,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 18,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 19,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 20,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 21,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 22,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 23,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 24,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 25,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 26,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 27,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 28,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 29,SQL_TEXT,NULL)))
FROM V$SQLTEXT_WITH_NEWLINES
WHERE ADDRESS = SI.SQL_ADDRESS AND
PIECE < 30
) SQL_TEXT
FROM sess si;

Create a zip file and download it

Add Content-length header describing size of zip file in bytes.

header("Content-type: application/zip"); 
header("Content-Disposition: attachment; filename=$archive_file_name");
header("Content-length: " . filesize($archive_file_name));
header("Pragma: no-cache"); 
header("Expires: 0"); 
readfile("$archive_file_name");

Also make sure that there is absolutely no white space before <? and after ?>. I see a space here:

?

 <?php
$file_names = array('iMUST Operating Manual V1.3a.pdf','iMUST Product Information Sheet.pdf');

Enable/Disable Anchor Tags using AngularJS

You may, redefine the a tag using angular directive:

angular.module('myApp').directive('a', function() {
  return {
    restrict: 'E',
    link: function(scope, elem, attrs) {
      if ('disabled' in attrs) {
        elem.on('click', function(e) {
          e.preventDefault(); // prevent link click
        });
      }
    }
  };
});

In html:

<a href="nextPage" disabled>Next</a>

Setting up and using environment variables in IntelliJ Idea

In addition to the above answer and restarting the IDE didn't do, try restarting "Jetbrains Toolbox" if you use it, this did it for me

How to edit incorrect commit message in Mercurial?

A little gem in the discussion above - thanks to @Codest and @Kevin Pullin. In TortoiseHg, there's a dropdown option adjacent to the commit button. Selecting "Amend current revision" brings back the comment and the list of files. SO useful.

How to access /storage/emulated/0/

Android recommends that you call Environment.getExternalStorageDirectory.getPath() instead of hardcoding /sdcard/ in path name. This returns the primary shared/external storage directory. So, if storage is emulated, this will return /storage/emulated/0. If you explore the device storage with a file explorer, the said directory will be /mnt/sdcard (confirmed on Xperia Z2 running Android 6).

How to use google maps without api key

Now you must have API key. You can generate that in google developer console. Here is LINK to the explanation.

assembly to compare two numbers

In TASM (x86 assembly) it can look like this:

cmp BL, BH
je EQUAL       ; BL = BH
jg GREATER     ; BL > BH
jmp LESS       ; BL < BH

in this case it compares two 8bit numbers that we temporarily store in the higher and the lower part of the register B. Alternatively you might also consider using jbe (if BL <= BH) or jge/jae (if BL >= BH).

Hopefully someone finds it helpful :)

Remove characters after specific character in string, then remove substring?

you can use .NET's built in method to remove the QueryString. i.e., Request.QueryString.Remove["whatever"];

here whatever in the [ ] is name of the querystring which you want to remove.

Try this... I hope this will help.

Persist javascript variables across pages?

Yes, using Cookies. But be careful, don't put too much in them (I think there is a limit at 4kb). But a few variables are ok.

If you need to store considerably more than that, check out @Annie's great tips in the other answer. For small time data storage, I would say Cookies are the easiest thing.

Note that cookies are stored client side.

Return current date plus 7 days

echo date('d-m-Y', strtotime('+7 days'));

Pentaho Data Integration SQL connection

Missing driver file.

This error is really common for people just getting started with PDI.

Drivers go in \pentaho\design-tools\data-integration\libext\JDBC for PDI. If you are using other tools in the Pentaho suite, you may need to copy drivers to additional locations for those tools. For reference, here are the appropriate folders for some of the other design tools:

  • Aggregation Designer: \pentaho\design-tools\aggregation-designer\drivers
  • Metadata Editor: \pentaho\design-tools\metadata-editor\libext\JDBC
  • Report Designer: \pentaho\design-tools\report-designer\lib\jdbc
  • Schema Workbench: \pentaho\design-tools\schema-workbench\drivers

If this transformation or job will run on another box, such as a test or production server, don't forget to include copying the jar file and restarting PDI or the Data Integration Server in your deployment considerations.

How to retry after exception?

increment your loop variable only when the try clause succeeds

Maven:Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.7:resources

I had this issue too because I was filtering /src/main/resources and forgot I had added a keystore (*.jks) binary to this directory.

Add a "resource" block with exclusions for binary files and your problem may be resolved.

<build>
  <finalName>somename</finalName>
  <testResources>
    <testResource>
      <directory>src/test/resources</directory>
      <filtering>false</filtering>
    </testResource>
  </testResources>
  <resources>
    <resource>
      <directory>src/main/resources</directory>
      <filtering>true</filtering>
      <excludes>
        <exclude>*.jks</exclude>
        <exclude>*.png</exclude>
      </excludes>        
    </resource>
  </resources>
...

add an element to int [] array in java

The length of an array is immutable in java. This means you can't change the size of an array once you have created it. If you initialised it with 2 elements, its length is 2. You can however use a different collection.

List<Integer> myList = new ArrayList<Integer>();
myList.add(5);
myList.add(7);

And with a wrapper method

public void addMember(Integer x) {
    myList.add(x);
};

Making LaTeX tables smaller?

http://en.wikibooks.org/wiki/LaTeX/Tables#Resize_tables talks about two ways to do this.

I used:

\scalebox{0.7}{
  \begin{tabular}
    ...
  \end{tabular}
}

How to hide output of subprocess in Python 2.7

Use subprocess.check_output (new in python 2.7). It will suppress stdout and raise an exception if the command fails. (It actually returns the contents of stdout, so you can use that later in your program if you want.) Example:

import subprocess
try:
    subprocess.check_output(['espeak', text])
except subprocess.CalledProcessError:
    # Do something

You can also suppress stderr with:

    subprocess.check_output(["espeak", text], stderr=subprocess.STDOUT)

For earlier than 2.7, use

import os
import subprocess
with open(os.devnull, 'w')  as FNULL:
    try:
        subprocess._check_call(['espeak', text], stdout=FNULL)
    except subprocess.CalledProcessError:
        # Do something

Here, you can suppress stderr with

        subprocess._check_call(['espeak', text], stdout=FNULL, stderr=FNULL)

How can I extract substrings from a string in Perl?

This just requires a small change to my last answer:

my ($guid, $scheme, $star) = $line =~ m{
    The [ ] Scheme [ ] GUID: [ ]
    ([a-zA-Z0-9-]+)          #capture the guid
    [ ]
    \(  (.+)  \)             #capture the scheme 
    (?:
        [ ]
        ([*])                #capture the star 
    )?                       #if it exists
}x;

How to assign colors to categorical variables in ggplot2 that have stable mapping?

Based on the very helpful answer by joran I was able to come up with this solution for a stable color scale for a boolean factor (TRUE, FALSE).

boolColors <- as.character(c("TRUE"="#5aae61", "FALSE"="#7b3294"))
boolScale <- scale_colour_manual(name="myboolean", values=boolColors)

ggplot(myDataFrame, aes(date, duration)) + 
  geom_point(aes(colour = myboolean)) +
  boolScale

Since ColorBrewer isn't very helpful with binary color scales, the two needed colors are defined manually.

Here myboolean is the name of the column in myDataFrame holding the TRUE/FALSE factor. date and duration are the column names to be mapped to the x and y axis of the plot in this example.

how to get domain name from URL

So if you just have a string and not a window.location you could use...

String.prototype.toUrl = function(){

if(!this && 0 < this.length)
{
    return undefined;
}
var original = this.toString();
var s = original;
if(!original.toLowerCase().startsWith('http'))
{
    s = 'http://' + original;
}

s = this.split('/');

var protocol = s[0];
var host = s[2];
var relativePath = '';

if(s.length > 3){
    for(var i=3;i< s.length;i++)
    {
        relativePath += '/' + s[i];
    }
}

s = host.split('.');
var domain = s[s.length-2] + '.' + s[s.length-1];    

return {
    original: original,
    protocol: protocol,
    domain: domain,
    host: host,
    relativePath: relativePath,
    getParameter: function(param)
    {
        return this.getParameters()[param];
    },
    getParameters: function(){
        var vars = [], hash;
        var hashes = this.original.slice(this.original.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }
};};

How to use.

var str = "http://en.wikipedia.org/wiki/Knopf?q=1&t=2";
var url = str.toUrl;

var host = url.host;
var domain = url.domain;
var original = url.original;
var relativePath = url.relativePath;
var paramQ = url.getParameter('q');
var paramT = url.getParamter('t');

What is the difference between React Native and React?

  1. React-Native is a framework for developing Android & iOS applications which shares 80% - 90% of Javascript code.

While React.js is a parent Javascript library for developing web applications.

  1. While you use tags like <View>, <Text> very frequently in React-Native, React.js uses web html tags like <div> <h1> <h2>, which are only synonyms in dictionary of web/mobile developments.

  2. For React.js you need DOM for path rendering of html tags, while for mobile application: React-Native uses AppRegistry to register your app.

I hope this is an easy explanation for quick differences/similarities in React.js and React-Native.

How to add a href link in PHP?

Just do it in HTML

<a href="https://www.google.com">Google</a>

Disable building workspace process in Eclipse

if needed programmatic from a PDE or JDT code:

public static void setWorkspaceAutoBuild(boolean flag) throws CoreException 
{
IWorkspace workspace = ResourcesPlugin.getWorkspace();
final IWorkspaceDescription description = workspace.getDescription();
description.setAutoBuilding(flag);
workspace.setDescription(description);
}

What is the most efficient way to get first and last line of a text file?

To read both the first and final line of a file you could...

  • open the file, ...
  • ... read the first line using built-in readline(), ...
  • ... seek (move the cursor) to the end of the file, ...
  • ... step backwards until you encounter EOL (line break) and ...
  • ... read the last line from there.
def readlastline(f):
    f.seek(-2, 2)              # Jump to the second last byte.
    while f.read(1) != b"\n":  # Until EOL is found ...
        f.seek(-2, 1)          # ... jump back, over the read byte plus one more.
    return f.read()            # Read all data from this point on.
    
with open(file, "rb") as f:
    first = f.readline()
    last = readlastline(f)

Jump to the second last byte directly to prevent trailing newline characters to cause empty lines to be returned*.

The current offset is pushed ahead by one every time a byte is read so the stepping backwards is done two bytes at a time, past the recently read byte and the byte to read next.

The whence parameter passed to fseek(offset, whence=0) indicates that fseek should seek to a position offset bytes relative to...

* As would be expected as the default behavior of most applications, including print and echo, is to append one to every line written and has no effect on lines missing trailing newline character.


Efficiency

1-2 million lines each and I have to do this for several hundred files.

I timed this method and compared it against against the top answer.

10k iterations processing a file of 6k lines totalling 200kB: 1.62s vs 6.92s.
100 iterations processing a file of 6k lines totalling 1.3GB: 8.93s vs 86.95.

Millions of lines would increase the difference a lot more.

Exakt code used for timing:

with open(file, "rb") as f:
    first = f.readline()     # Read and store the first line.
    for last in f: pass      # Read all lines, keep final value.

Amendment

A more complex, and harder to read, variation to address comments and issues raised since.

  • Return empty string when parsing empty file, raised by comment.
  • Return all content when no delimiter is found, raised by comment.
  • Avoid relative offsets to support text mode, raised by comment.
  • UTF16/UTF32 hack, noted by comment.

Also adds support for multibyte delimiters, readlast(b'X<br>Y', b'<br>', fixed=False).

Please note that this variation is really slow for large files because of the non-relative offsets needed in text mode. Modify to your need, or do not use it at all as you're probably better off using f.readlines()[-1] with files opened in text mode.

#!/bin/python3

from os import SEEK_END

def readlast(f, sep, fixed=True):
    r"""Read the last segment from a file-like object.

    :param f: File to read last line from.
    :type  f: file-like object
    :param sep: Segment separator (delimiter).
    :type  sep: bytes, str
    :param fixed: Treat data in ``f`` as a chain of fixed size blocks.
    :type  fixed: bool
    :returns: Last line of file.
    :rtype: bytes, str
    """
    bs   = len(sep)
    step = bs if fixed else 1
    if not bs:
        raise ValueError("Zero-length separator.")
    try:
        o = f.seek(0, SEEK_END)
        o = f.seek(o-bs-step)    # - Ignore trailing delimiter 'sep'.
        while f.read(bs) != sep: # - Until reaching 'sep': Read sep-sized block
            o = f.seek(o-step)   #  and then seek to the block to read next.
    except (OSError,ValueError): # - Beginning of file reached.
        f.seek(0)
    return f.read()

def test_readlast():
    from io import BytesIO, StringIO
    
    # Text mode.
    f = StringIO("first\nlast\n")
    assert readlast(f, "\n") == "last\n"
    
    # Bytes.
    f = BytesIO(b'first|last')
    assert readlast(f, b'|') == b'last'
    
    # Bytes, UTF-8.
    f = BytesIO("X\nY\n".encode("utf-8"))
    assert readlast(f, b'\n').decode() == "Y\n"
    
    # Bytes, UTF-16.
    f = BytesIO("X\nY\n".encode("utf-16"))
    assert readlast(f, b'\n\x00').decode('utf-16') == "Y\n"
  
    # Bytes, UTF-32.
    f = BytesIO("X\nY\n".encode("utf-32"))
    assert readlast(f, b'\n\x00\x00\x00').decode('utf-32') == "Y\n"
    
    # Multichar delimiter.
    f = StringIO("X<br>Y")
    assert readlast(f, "<br>", fixed=False) == "Y"
    
    # Make sure you use the correct delimiters.
    seps = { 'utf8': b'\n', 'utf16': b'\n\x00', 'utf32': b'\n\x00\x00\x00' }
    assert "\n".encode('utf8' )     == seps['utf8']
    assert "\n".encode('utf16')[2:] == seps['utf16']
    assert "\n".encode('utf32')[4:] == seps['utf32']
    
    # Edge cases.
    edges = (
        # Text , Match
        (""    , ""  ), # Empty file, empty string.
        ("X"   , "X" ), # No delimiter, full content.
        ("\n"  , "\n"),
        ("\n\n", "\n"),
        # UTF16/32 encoded U+270A (b"\n\x00\n'\n\x00"/utf16)
        (b'\n\xe2\x9c\x8a\n'.decode(), b'\xe2\x9c\x8a\n'.decode()),
    )
    for txt, match in edges:
        for enc,sep in seps.items():
            assert readlast(BytesIO(txt.encode(enc)), sep).decode(enc) == match

if __name__ == "__main__":
    import sys
    for path in sys.argv[1:]:
        with open(path) as f:
            print(f.readline()    , end="")
            print(readlast(f,"\n"), end="")

React Js: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

on your Promise response you requested

response.json() 

but this works well if your server sends json response in return especially if you're using Node Js on the server side

So check again and make sure your server sends json as response as said if its NodeJS the response could be

res.json(YOUR-DATA-RESPONSE)

Passing data through intent using Serializable

Try to pass the serializable list using Bundle.Serializable:

Bundle bundle = new Bundle();
bundle.putSerializable("value", all_thumbs);
intent.putExtras(bundle);

And in SomeClass Activity get it as:

Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();

List<Thumbnail> thumbs=
               (List<Thumbnail>)bundle.getSerializable("value");

Execute PHP scripts within Node.js web server

You can run PHP as with any web-server, using the SPHP module for node.
It's compatible but not dependent on express.
It also supports websockets requests on the HTTP port.
Its biased for speed under small load, rather then saving resources.

To install in node:

npm install sphp

in you app:

var express = require('express');
var sphp = require('sphp');

var app = express();
var server = app.listen(8080);

app.use(sphp.express('public/'));
app.use(express.static('public/'));

For more information, look at https://github.com/paragi/sphp

I'm slightly biased too because I'm the author :)

Converting SVG to PNG using C#

There is a much easier way using the library http://svg.codeplex.com/ (Newer version @GIT, @NuGet). Here is my code

var byteArray = Encoding.ASCII.GetBytes(svgFileContents);
using (var stream = new MemoryStream(byteArray))
{
    var svgDocument = SvgDocument.Open(stream);
    var bitmap = svgDocument.Draw();
    bitmap.Save(path, ImageFormat.Png);
}

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in

$result2 is resource link not a string to echo it or to replace some of its parts with str_replace().

http://php.net/manual/en/function.mysql-query.php

File.Move Does Not Work - File Already Exists

You can do a P/Invoke to MoveFileEx() - pass 11 for flags (MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)

[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
static extern bool MoveFileEx(string existingFileName, string newFileName, int flags);

Or, you can just call

Microsoft.VisualBasic.FileIO.FileSystem.MoveFile(existingFileName, newFileName, true);

after adding Microsoft.VisualBasic as a reference.

Sqlite: CURRENT_TIMESTAMP is in GMT, not the timezone of the machine

I think this might help.

SELECT datetime(strftime('%s','now'), 'unixepoch', 'localtime');

How to wait for async method to complete?

Avoid async void. Have your methods return Task instead of void. Then you can await them.

Like this:

private async Task RequestToSendOutputReport(List<byte[]> byteArrays)
{
    foreach (byte[] b in byteArrays)
    {
        while (condition)
        {
            // we'll typically execute this code many times until the condition is no longer met
            Task t = SendOutputReportViaInterruptTransfer();
            await t;
        }

        // read some data from device; we need to wait for this to return
        await RequestToGetInputReport();
    }
}

private async Task RequestToGetInputReport()
{
    // lots of code prior to this
    int bytesRead = await GetInputReportViaInterruptTransfer();
}

How to synchronize or lock upon variables in Java?

That's pretty easy:

class Sample {
    private String message = null;
    private final Object lock = new Object();

    public void newMessage(String x) {
        synchronized (lock) {
            message = x;
        }
    }

    public String getMessage() {
        synchronized (lock) {
            String temp = message;
            message = null;
            return temp;
        }
    }
}

Note that I didn't either make the methods themselves synchronized or synchronize on this. I firmly believe that it's a good idea to only acquire locks on objects which only your code has access to, unless you're deliberately exposing the lock. It makes it a lot easier to reassure yourself that nothing else is going to acquire locks in a different order to your code, etc.

Listing all permutations of a string/integer

If performance and memory is an issue, I suggest this very efficient implementation. According to Heap's algorithm in Wikipedia, it should be the fastest. Hope it will fits your need :-) !

Just as comparison of this with a Linq implementation for 10! (code included):

  • This: 36288000 items in 235 millisecs
  • Linq: 36288000 items in 50051 millisecs

    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Runtime.CompilerServices;
    using System.Text;
    
    namespace WpfPermutations
    {
        /// <summary>
        /// EO: 2016-04-14
        /// Generator of all permutations of an array of anything.
        /// Base on Heap's Algorithm. See: https://en.wikipedia.org/wiki/Heap%27s_algorithm#cite_note-3
        /// </summary>
        public static class Permutations
        {
            /// <summary>
            /// Heap's algorithm to find all pmermutations. Non recursive, more efficient.
            /// </summary>
            /// <param name="items">Items to permute in each possible ways</param>
            /// <param name="funcExecuteAndTellIfShouldStop"></param>
            /// <returns>Return true if cancelled</returns> 
            public static bool ForAllPermutation<T>(T[] items, Func<T[], bool> funcExecuteAndTellIfShouldStop)
            {
                int countOfItem = items.Length;
    
                if (countOfItem <= 1)
                {
                    return funcExecuteAndTellIfShouldStop(items);
                }
    
                var indexes = new int[countOfItem];
                for (int i = 0; i < countOfItem; i++)
                {
                    indexes[i] = 0;
                }
    
                if (funcExecuteAndTellIfShouldStop(items))
                {
                    return true;
                }
    
                for (int i = 1; i < countOfItem;)
                {
                    if (indexes[i] < i)
                    { // On the web there is an implementation with a multiplication which should be less efficient.
                        if ((i & 1) == 1) // if (i % 2 == 1)  ... more efficient ??? At least the same.
                        {
                            Swap(ref items[i], ref items[indexes[i]]);
                        }
                        else
                        {
                            Swap(ref items[i], ref items[0]);
                        }
    
                        if (funcExecuteAndTellIfShouldStop(items))
                        {
                            return true;
                        }
    
                        indexes[i]++;
                        i = 1;
                    }
                    else
                    {
                        indexes[i++] = 0;
                    }
                }
    
                return false;
            }
    
            /// <summary>
            /// This function is to show a linq way but is far less efficient
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="list"></param>
            /// <param name="length"></param>
            /// <returns></returns>
            static IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<T> list, int length)
            {
                if (length == 1) return list.Select(t => new T[] { t });
    
                return GetPermutations(list, length - 1)
                    .SelectMany(t => list.Where(e => !t.Contains(e)),
                        (t1, t2) => t1.Concat(new T[] { t2 }));
            }
    
            /// <summary>
            /// Swap 2 elements of same type
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="a"></param>
            /// <param name="b"></param>
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            static void Swap<T>(ref T a, ref T b)
            {
                T temp = a;
                a = b;
                b = temp;
            }
    
            /// <summary>
            /// Func to show how to call. It does a little test for an array of 4 items.
            /// </summary>
            public static void Test()
            {
                ForAllPermutation("123".ToCharArray(), (vals) =>
                {
                    Debug.Print(String.Join("", vals));
                    return false;
                });
    
                int[] values = new int[] { 0, 1, 2, 4 };
    
                Debug.Print("Non Linq");
                ForAllPermutation(values, (vals) =>
                {
                    Debug.Print(String.Join("", vals));
                    return false;
                });
    
                Debug.Print("Linq");
                foreach(var v in GetPermutations(values, values.Length))
                {
                    Debug.Print(String.Join("", v));
                }
    
                // Performance
                int count = 0;
    
                values = new int[10];
                for(int n = 0; n < values.Length; n++)
                {
                    values[n] = n;
                }
    
                Stopwatch stopWatch = new Stopwatch();
                stopWatch.Reset();
                stopWatch.Start();
    
                ForAllPermutation(values, (vals) =>
                {
                    foreach(var v in vals)
                    {
                        count++;
                    }
                    return false;
                });
    
                stopWatch.Stop();
                Debug.Print($"Non Linq {count} items in {stopWatch.ElapsedMilliseconds} millisecs");
    
                count = 0;
                stopWatch.Reset();
                stopWatch.Start();
    
                foreach (var vals in GetPermutations(values, values.Length))
                {
                    foreach (var v in vals)
                    {
                        count++;
                    }
                }
    
                stopWatch.Stop();
                Debug.Print($"Linq {count} items in {stopWatch.ElapsedMilliseconds} millisecs");
    
            }
        }
    }
    

Move cursor to end of file in vim

No need to explicitly go to the end of line before doing a, use A;
Append text at the end of line [count] times

<ESC>GA

How to sort mongodb with pymongo

Sort by _id descending:

collection.find(filter={"keyword": keyword}, sort=[( "_id", -1 )])

Sort by _id ascending:

collection.find(filter={"keyword": keyword}, sort=[( "_id", 1 )])

How can I check if a single character appears in a string?

String.contains(String) or String.indexOf(String) - suggested

"abc".contains("Z"); // false - correct
"zzzz".contains("Z"); // false - correct
"Z".contains("Z"); // true - correct
"and".contains(""); // true - correct
"and".contains(""); // false - correct
"and".indexOf(""); // 0 - correct
"and".indexOf(""); // -1 - correct

String.indexOf(int) and carefully considered String.indexOf(char) with char to int widening

"and".indexOf("".charAt(0)); // 0 though incorrect usage has correct output due to portion of correct data
"and".indexOf("".charAt(0)); // 0 -- incorrect usage and ambiguous result
"and".indexOf("".codePointAt(0)); // -1 -- correct usage and correct output

The discussions around character is ambiguous in Java world

can the value of char or Character considered as single character?

No. In the context of unicode characters, char or Character can sometimes be part of a single character and should not be treated as a complete single character logically.

if not, what should be considered as single character (logically)?

Any system supporting character encodings for Unicode characters should consider unicode's codepoint as single character.

So Java should do that very clear & loud rather than exposing too much of internal implementation details to users.

String class is bad at abstraction (though it requires confusingly good amount of understanding of its encapsulations to understand the abstraction and hence an anti-pattern).

How is it different from general char usage?

char can be only be mapped to a character in Basic Multilingual Plane.

Only codePoint - int can cover the complete range of Unicode characters.

Why is this difference?

char is internally treated as 16-bit unsigned value and could not represent all the unicode characters using UTF-16 internal representation using only 2-bytes. Sometimes, values in a 16-bit range have to be combined with another 16-bit value to correctly define character.

Without getting too verbose, the usage of indexOf, charAt, length and such methods should be more explicit. Sincerely hoping Java will add new UnicodeString and UnicodeCharacter classes with clearly defined abstractions.

Reason to prefer contains and not indexOf(int)

  1. Practically there are many code flows that treat a logical character as char in java.
  2. In Unicode context, char is not sufficient
  3. Though the indexOf takes in an int, char to int conversion masks this from the user and user might do something like str.indexOf(someotherstr.charAt(0))(unless the user is aware of the exact context)
  4. So, treating everything as CharSequence (aka String) is better
    public static void main(String[] args) {
        System.out.println("and".indexOf("".charAt(0))); // 0 though incorrect usage has correct output due to portion of correct data
        System.out.println("and".indexOf("".charAt(0))); // 0 -- incorrect usage and ambiguous result
        System.out.println("and".indexOf("".codePointAt(0))); // -1 -- correct usage and correct output
        System.out.println("and".contains("")); // true - correct
        System.out.println("and".contains("")); // false - correct
    }

Twitter bootstrap scrollable modal

How about the below solution? It worked for me. Try this:

.modal .modal-body {
    max-height: 420px;
    overflow-y: auto;
}

Details:

  1. remove overflow-y: auto; or overflow: auto; from .modal class (important)
  2. remove max-height: 400px; from .modal class (important)
  3. Add max-height: 400px; to .modal .modal-body (or what ever, can be 420px or less, but would not go more than 450px)
  4. Add overflow-y: auto; to .modal .modal-body

Done, only body will scroll.

How can I save a base64-encoded image to disk?

I also had to save Base64 encoded images that are part of data URLs, so I ended up making a small npm module to do it in case I (or someone else) needed to do it again in the future. It's called ba64.

Simply put, it takes a data URL with a Base64 encoded image and saves the image to your file system. It can save synchronously or asynchronously. It also has two helper functions, one to get the file extension of the image, and the other to separate the Base64 encoding from the data: scheme prefix.

Here's an example:

var ba64 = require("ba64"),
    data_url = "data:image/jpeg;base64,[Base64 encoded image goes here]";

// Save the image synchronously.
ba64.writeImageSync("myimage", data_url); // Saves myimage.jpeg.

// Or save the image asynchronously.
ba64.writeImage("myimage", data_url, function(err){
    if (err) throw err;

    console.log("Image saved successfully");

    // do stuff
});

Install it: npm i ba64 -S. Repo is on GitHub: https://github.com/HarryStevens/ba64.

P.S. It occurred to me later that ba64 is probably a bad name for the module since people may assume it does Base64 encoding and decoding, which it doesn't (there are lots of modules that already do that). Oh well.

How do you disable browser Autocomplete on web form field / input tag?

I wanted something that took the field management completely out of the browser's hands, so to speak. In this example, there's a single standard text input field to capture a password — no email, user name etc...

<input id='input_password' type='text' autocomplete='off' autofocus>

There's a variable named "input", set to be an empty string...

var input = "";

The field events are monitored by JQuery...

  1. On focus, the field content and the associated "input" variable are always cleared.
  2. On keypress, any alphanumeric character, as well as some defined symbols, are appended to the "input" variable, and the field input is replaced with a bullet character. Additionally, when the Enter key is pressed, the typed characters (stored in the "input" variable) are sent to the server via Ajax. (See "Server Details" below.)
  3. On keyup, the Home, End, and Arrow keys cause the "input" variable and field values to be flushed. (I could have gotten fancy with arrow navigation and the focus event, and used .selectionStart to figure out where the user had clicked or was navigating, but it's not worth the effort for a password field.) Additionally, pressing the Backspace key truncates both the variable and field content accordingly.

$("#input_password").off().on("focus", function(event) {
    $(this).val("");
    input = "";

}).on("keypress", function(event) {
    event.preventDefault();

    if (event.key !== "Enter" && event.key.match(/^[0-9a-z!@#\$%&*-_]/)) {
        $(this).val( $(this).val() + "•" );
        input += event.key;
    }
    else if (event.key == "Enter") {
        var params = {};
        params.password = input;

        $.post(SERVER_URL, params, function(data, status, ajax) {
            location.reload();
        });
    }

}).on("keyup", function(event) {
    var navigationKeys = ["Home", "End", "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"];
    if ($.inArray(event.key, navigationKeys) > -1) {
        event.preventDefault();
        $(this).val("");
        input = "";
    }
    else if (event.key == "Backspace") {
        var length = $(this).val().length - 1 > 0 ? $(this).val().length : 0;
        input = input.substring(0, length);
    }
});

Front-End Summary

In essence, this gives the browser nothing useful to capture. Even if it overrides the autocomplete setting, and/or presents a dropdown with previously entered values, all it has is bullets stored for the field value.


Server Details (optional reading)

As shown above, Javascript executes location.reload() as soon as the server returns a JSON response. (This logon technique is for access to a restricted administration tool. Some of the overkill, related to the cookie content, could be skipped for a more generalized implementation.) Here are the details:

  • When a user navigates to the site, the server looks for a legitimate cookie.
  • If there is no cookie, the logon page is presented. When the user enters a password and it is sent via Ajax, the server confirms the password and also checks to see if the user's IP is in an Authorized IP list.
  • If either the password or IP are not recognized, the server doesn't generate a cookie, so when the page reloads, the user sees the same logon page.
  • If both the password and IP are recognized, the server generates a cookie that has a ten-minute life span, and it also stores two scrambled values that correspond with the time-frame and IP.
  • When the page reloads, the server finds the cookie and verifies that the scrambled values are correct (i.e., that the time-frame corresponds with the cookie's date and that the IP is the same).
  • The process of authenticating and updating the cookie is repeated every time the user interacts with the server, whether they are logging in, displaying data, or updating a record.
  • If at all times the cookie's values are correct, the server presents the full website (if the user is logging in) or fulfills whatever display or update request was submitted.
  • If at any time the cookie's values are not correct, the server removes the current cookie which then, upon reload, causes the logon page to be re-displayed.

Sort a list of lists with a custom compare function

You need to slightly modify your compare function and use functools.cmp_to_key to pass it to sorted. Example code:

import functools

lst = [list(range(i, i+5)) for i in range(5, 1, -1)]

def fitness(item):
    return item[0]+item[1]+item[2]+item[3]+item[4]
def compare(item1, item2):
    return fitness(item1) - fitness(item2)

sorted(lst, key=functools.cmp_to_key(compare))

Output:

[[2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8], [5, 6, 7, 8, 9]]

Works :)

What should main() return in C and C++?

Returning 0 should tell the programmer that the program has successfully finished the job.

Accessing a resource via codebehind in WPF

I got the resources on C# (Desktop WPF W/ .NET Framework 4.8) using the code below

{DefaultNamespace}.Properties.Resources.{ResourceName}

How to pass datetime from c# to sql correctly?

You've already done it correctly by using a DateTime parameter with the value from the DateTime, so it should already work. Forget about ToString() - since that isn't used here.

If there is a difference, it is most likely to do with different precision between the two environments; maybe choose a rounding (seconds, maybe?) and use that. Also keep in mind UTC/local/unknown (the DB has no concept of the "kind" of date; .NET does).

I have a table and the date-times in it are in the format: 2011-07-01 15:17:33.357

Note that datetimes in the database aren't in any such format; that is just your query-client showing you white lies. It is stored as a number (and even that is an implementation detail), because humans have this odd tendency not to realise that the date you've shown is the same as 40723.6371916281. Stupid humans. By treating it simply as a "datetime" throughout, you shouldn't get any problems.

Spring transaction REQUIRED vs REQUIRES_NEW : Rollback Transaction

Using REQUIRES_NEW is only relevant when the method is invoked from a transactional context; when the method is invoked from a non-transactional context, it will behave exactly as REQUIRED - it will create a new transaction.

That does not mean that there will only be one single transaction for all your clients - each client will start from a non-transactional context, and as soon as the the request processing will hit a @Transactional, it will create a new transaction.

So, with that in mind, if using REQUIRES_NEW makes sense for the semantics of that operation - than I wouldn't worry about performance - this would textbook premature optimization - I would rather stress correctness and data integrity and worry about performance once performance metrics have been collected, and not before.

On rollback - using REQUIRES_NEW will force the start of a new transaction, and so an exception will rollback that transaction. If there is also another transaction that was executing as well - that will or will not be rolled back depending on if the exception bubbles up the stack or is caught - your choice, based on the specifics of the operations. Also, for a more in-depth discussion on transactional strategies and rollback, I would recommend: «Transaction strategies: Understanding transaction pitfalls», Mark Richards.

What is WEB-INF used for in a Java EE web application?

You should put in WEB-INF any pages, or pieces of pages, that you do not want to be public. Usually, JSP or facelets are found outside WEB-INF, but in this case they are easily accesssible for any user. In case you have some authorization restrictions, WEB-INF can be used for that.

WEB-INF/lib can contain 3rd party libraries which you do not want to pack at system level (JARs can be available for all the applications running on your server), but only for this particular applciation.

Generally speaking, many configurations files also go into WEB-INF.

As for WEB-INF/classes - it exists in any web-app, because that is the folder where all the compiled sources are placed (not JARS, but compiled .java files that you wrote yourself).

Search for "does-not-contain" on a DataFrame in pandas

You can use the invert (~) operator (which acts like a not for boolean data):

new_df = df[~df["col"].str.contains(word)]

, where new_df is the copy returned by RHS.

contains also accepts a regular expression...


If the above throws a ValueError, the reason is likely because you have mixed datatypes, so use na=False:

new_df = df[~df["col"].str.contains(word, na=False)]

Or,

new_df = df[df["col"].str.contains(word) == False]

Writing JSON object to a JSON file with fs.writeFileSync

Here's a variation, using the version of fs that uses promises:

const fs = require('fs');

await fs.promises.writeFile('../data/phraseFreqs.json', JSON.stringify(output)); // UTF-8 is default

Skipping Incompatible Libraries at compile

That message isn't actually an error - it's just a warning that the file in question isn't of the right architecture (e.g. 32-bit vs 64-bit, wrong CPU architecture). The linker will keep looking for a library of the right type.

Of course, if you're also getting an error along the lines of can't find lPI-Http then you have a problem :-)

It's hard to suggest what the exact remedy will be without knowing the details of your build system and makefiles, but here are a couple of shots in the dark:

  1. Just to check: usually you would add flags to CFLAGS rather than CTAGS - are you sure this is correct? (What you have may be correct - this will depend on your build system!)
  2. Often the flag needs to be passed to the linker too - so you may also need to modify LDFLAGS

If that doesn't help - can you post the full error output, plus the actual command (e.g. gcc foo.c -m32 -Dxxx etc) that was being executed?

Access a URL and read Data with R

Beside of read.csv(url("...")) you also can use read.table("http://...").

Example:

> sample <- read.table("http://www.ats.ucla.edu/stat/examples/ara/angell.txt")
> sample
                V1   V2   V3   V4 V5
1        Rochester 19.0 20.6 15.0  E
2         Syracuse 17.0 15.6 20.2  E
...
43         Atlanta  4.2 70.6 32.6  S
>