Programs & Examples On #Greenplum

Greenplum is the worlds first open-source massively parallel processing database based on PostgreSQL.It provides powerful and rapid analytics on petabyte scale data volumes. Uniquely geared toward big data analytics, Greenplum Database is powered by the world’s most advanced cost-based query optimizer delivering high analytical query performance on large data volumes.

How do I pass the this context to a function?

Javascripts .call() and .apply() methods allow you to set the context for a function.

var myfunc = function(){
    alert(this.name);
};

var obj_a = {
    name:  "FOO"
};

var obj_b = {
    name:  "BAR!!"
};

Now you can call:

myfunc.call(obj_a);

Which would alert FOO. The other way around, passing obj_b would alert BAR!!. The difference between .call() and .apply() is that .call() takes a comma separated list if you're passing arguments to your function and .apply() needs an array.

myfunc.call(obj_a, 1, 2, 3);
myfunc.apply(obj_a, [1, 2, 3]);

Therefore, you can easily write a function hook by using the apply() method. For instance, we want to add a feature to jQuerys .css() method. We can store the original function reference, overwrite the function with custom code and call the stored function.

var _css = $.fn.css;
$.fn.css = function(){
   alert('hooked!');
   _css.apply(this, arguments);
};

Since the magic arguments object is an array like object, we can just pass it to apply(). That way we guarantee, that all parameters are passed through to the original function.

Mac install and open mysql using terminal

If you have your MySQL server up and running, then you just need a client to connect to it and start practicing. One is the mysql-client, which is a command-line tool, or you can use phpMyAdmin, which is a web-based tool.

How do I get the YouTube video ID from a URL?

/^.*(youtu.be\/|v\/|e\/|u\/\w+\/|embed\/|v=)([^#\&\?]*).*/

Tested on:

  • http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0
  • http://www.youtube.com/embed/0zM3nApSvMg?rel=0
  • http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index
  • http://www.youtube.com/watch?v=0zM3nApSvMg
  • http://youtu.be/0zM3nApSvMg
  • http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s
  • http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/KdwsulMb8EQ
  • http://youtu.be/dQw4w9WgXcQ
  • http://www.youtube.com/embed/dQw4w9WgXcQ
  • http://www.youtube.com/v/dQw4w9WgXcQ
  • http://www.youtube.com/e/dQw4w9WgXcQ
  • http://www.youtube.com/watch?v=dQw4w9WgXcQ
  • http://www.youtube.com/?v=dQw4w9WgXcQ
  • http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ
  • http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQ
  • http://www.youtube.com/user/IngridMichaelsonVEVO#p/u/11/KdwsulMb8EQ
  • http://www.youtube-nocookie.com/v/6L3ZvIMwZFM?version=3&hl=en_US&rel=0

Inspired by this other answer.

How can I get the URL of the current tab from a Google Chrome extension?

Hi here is an Google Chrome Sample which emails the current Site to an friend. The Basic idea behind is what you want...first of all it fetches the content of the page (not interessting for you)...afterwards it gets the URL (<-- good part)

Additionally it is a nice working code example, which i prefer motstly over reading Documents.

Can be found here: Email this page

cd into directory without having permission

You've got several options:

  • Use a different user account, one with execute permissions on that directory.
  • Change the permissions on the directory to allow your user account execute permissions.
    • Either use chmod(1) to change the permissions or
    • Use the setfacl(1) command to add an access control list entry for your user account. (This also requires mounting the filesystem with the acl option; see mount(8) and fstab(5) for details on the mount parameter.)

It's impossible to suggest the correct approach without knowing more about the problem; why are the directory permissions set the way they are? Why do you need access to that directory?

@UniqueConstraint and @Column(unique = true) in hibernate annotation

From the Java EE documentation:

public abstract boolean unique

(Optional) Whether the property is a unique key. This is a shortcut for the UniqueConstraint annotation at the table level and is useful for when the unique key constraint is only a single field. This constraint applies in addition to any constraint entailed by primary key mapping and to constraints specified at the table level.

See doc

How can I suppress column header output for a single SQL statement?

You can fake it like this:

-- with column headings 
select column1, column2 from some_table;

-- without column headings
select column1 as '', column2 as '' from some_table;

How can I generate a list of files with their absolute path in Linux?

This will give the canonical path (will resolve symlinks): realpath FILENAME

If you want canonical path to the symlink itself, then: realpath -s FILENAME

How do I mock an autowired @Value field in Spring with Mockito?

You can use this magic Spring Test annotation :

@TestPropertySource(properties = { "my.spring.property=20" }) 

see org.springframework.test.context.TestPropertySource

For example, this is the test class :

@ContextConfiguration(classes = { MyTestClass.Config.class })
@TestPropertySource(properties = { "my.spring.property=20" })
public class MyTestClass {

  public static class Config {
    @Bean
    MyClass getMyClass() {
      return new MyClass ();
    }
  }

  @Resource
  private MyClass myClass ;

  @Test
  public void myTest() {
   ...

And this is the class with the property :

@Component
public class MyClass {

  @Value("${my.spring.property}")
  private int mySpringProperty;
   ...

How to import component into another root component in Angular 2

above answers In simple words, you have to register under @NgModule's

declarations: [
    AppComponent, YourNewComponentHere
  ] 

of app.module.ts

do not forget to import that component.

How can I express that two values are not equal to eachother?

If the class implements comparable, you could also do

int compRes = a.compareTo(b);
if(compRes < 0 || compRes > 0)
    System.out.println("not equal");
else
    System.out.println("equal);

doesn't use a !, though not particularly useful, or readable....

How do I create a shortcut via command-line in Windows?

You could use a PowerShell command. Stick this in your batch script and it'll create a shortcut to %~f0 in %userprofile%\Start Menu\Programs\Startup:

powershell "$s=(New-Object -COM WScript.Shell).CreateShortcut('%userprofile%\Start Menu\Programs\Startup\%~n0.lnk');$s.TargetPath='%~f0';$s.Save()"

If you prefer not to use PowerShell, you could use mklink to make a symbolic link. Syntax:

mklink saveShortcutAs targetOfShortcut

See mklink /? in a console window for full syntax, and this web page for further information.

In your batch script, do:

mklink "%userprofile%\Start Menu\Programs\Startup\%~nx0" "%~f0"

The shortcut created isn't a traditional .lnk file, but it should work the same nevertheless. Be advised that this will only work if the .bat file is run from the same drive as your startup folder. Also, apparently admin rights are required to create symbolic links.

Continuous CSS rotation animation on hover, animated back to 0deg on hover out

The solution is to set the default value in your .elem. But this annimation work fine with -moz but not yet implement in -webkit

Look at the fiddle I updated from yours : http://jsfiddle.net/DoubleYo/4Vz63/1648/

It works fine with Firefox but not with Chrome

_x000D_
_x000D_
.elem{_x000D_
    position: absolute;_x000D_
    top: 40px;_x000D_
    left: 40px;_x000D_
    width: 0; _x000D_
    height: 0;_x000D_
    border-style: solid;_x000D_
    border-width: 75px;_x000D_
    border-color: red blue green orange;_x000D_
    transition-property: transform;_x000D_
    transition-duration: 1s;_x000D_
}_x000D_
.elem:hover {_x000D_
    animation-name: rotate; _x000D_
    animation-duration: 2s; _x000D_
    animation-iteration-count: infinite;_x000D_
    animation-timing-function: linear;_x000D_
}_x000D_
_x000D_
@keyframes rotate {_x000D_
    from {transform: rotate(0deg);}_x000D_
    to {transform: rotate(360deg);}_x000D_
}
_x000D_
<div class="elem"></div>
_x000D_
_x000D_
_x000D_

Deleting specific rows from DataTable

I have a dataset in my app and I went to set changes (deleting a row) to it but ds.tabales["TableName"] is read only. Then I found this solution.

It's a wpf C# app,

try {
    var results = from row in ds.Tables["TableName"].AsEnumerable() where row.Field<string>("Personalid") == "47" select row;                
    foreach (DataRow row in results) {
        ds.Tables["TableName"].Rows.Remove(row);                 
    }           
}

Conditionally ignoring tests in JUnit 4

In JUnit 4, another option for you may be to create an annotation to denote that the test needs to meet your custom criteria, then extend the default runner with your own and using reflection, base your decision on the custom criteria. It may look something like this:

public class CustomRunner extends BlockJUnit4ClassRunner {
    public CTRunner(Class<?> klass) throws initializationError {
        super(klass);
    }

    @Override
    protected boolean isIgnored(FrameworkMethod child) {
        if(shouldIgnore()) {
            return true;
        }
        return super.isIgnored(child);
    }

    private boolean shouldIgnore(class) {
        /* some custom criteria */
    }
}

Matplotlib figure facecolor (background color)

savefig has its own parameter for facecolor. I think an even easier way than the accepted answer is to set them globally just once, instead of putting facecolor=fig.get_facecolor() every time:

plt.rcParams['axes.facecolor']='red'
plt.rcParams['savefig.facecolor']='red'

How can I remove the outline around hyperlinks images?

This works perfectly for me

a img {border:none;}

Convert audio files to mp3 using ffmpeg

https://trac.ffmpeg.org/wiki/Encode/MP3

VBR Encoding:

ffmpeg -vn -ar 44100 -ac 2 -q:a 1 -codec:a libmp3lame output.mp3

Update ViewPager dynamically?

For some reason none of the answers worked for me so I had to override the restoreState method without calling super in my fragmentStatePagerAdapter. Code:

private class MyAdapter extends FragmentStatePagerAdapter {

    // [Rest of implementation]

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {}

}

Random row selection in Pandas dataframe

Actually this will give you repeated indices np.random.random_integers(0, len(df), N) where N is a large number.

Find CRLF in Notepad++

[\r\n]+ should work too

Update March, 26th 2012, release date of Notepad++ 6.0:

OMG, it actually does work now!!!

PCRE regexp in Notepad++


Original answer 2008 (Notepad++ 4.x) - 2009-2010-2011 (Notepad++ 5.x)

Actually no, it does not seem to work with regexp...

But if you have Notepad++ 5.x, you can use the 'extended' search mode and look for \r\n. That does find all your CRLF.

(I realize this is the same answer than the others, but again, 'extended mode' is only available with Notepad++ 4.9, 5.x and more)


Since April 2009, you have a wiki article on the Notepad++ site on this topic:
"How To Replace Line Ends, thus changing the line layout".
(mentioned by georgiecasey in his/her answer below)

Some relevant extracts includes the following search processes:

Simple search (Ctrl+F), Search Mode = Normal

You can select an EOL in the editing window.

  • Just move the cursor to the end of the line, and type Shift+Right Arrow.
  • or, to select EOL with the mouse, start just at the line end and drag to the start of the next line; dragging to the right of the EOL won't work. You can manually copy the EOL and paste it into the field for Unix files (LF-only).

Simple search (Ctrl+F), Search Mode = Extended

The "Extended" option shows \n and \r as characters that could be matched.
As with the Normal search mode, Notepad++ is looking for the exact character.
Searching for \r in a UNIX-format file will not find anything, but searching for \n will. Similarly, a Macintosh-format file will contain \r but not \n.

Simple search (Ctrl+F), Search Mode = Regular expression

Regular expressions use the characters ^ and $ to anchor the match string to the beginning or end of the line. For instance, searching for return;$ will find occurrences of "return;" that occur with no subsequent text on that same line. The anchor characters work identically in all file formats.
The '.' dot metacharacter does not match line endings.

[Tested in Notepad++ 5.8.5]: a regular expression search with an explicit \r or \n does not work (contrary to the Scintilla documentation).
Neither does a search on an explicit (pasted) LF, or on the (invisible) EOL characters placed in the field when an EOL is selected. Advanced search (Ctrl+R) without regexp

Ctrl+M will insert something that matches newlines. They will be replaced by the replace string.
I recommend this method as the most reliable, unless you really need to use regex.
As an example, to remove every second newline in a double spaced file, enter Ctrl+M twice in the search string box, and once in the replace string box.

Advanced search (Ctrl+R) with Regexp.

Neither Ctrl+M, $ nor \r\n are matched.


The same wiki also mentions the Hex editor alternative:

  • Type the new string at the beginning of the document.
  • Then select to view the document in Hex mode.
  • Select one of the new lines and hit Ctrl+H.
  • While you have the Replace dialog box up, select on the background the new replacement string and Ctrl+C copy it to paste it in the Replace with text input.
  • Then Replace or Replace All as you wish.

Note: the character selected for new line usually appears as 0a.
It may have a different value if the file is in Windows Format. In that case you can always go to Edit -> EOL Conversion -> Convert to Unix Format, and after the replacement switch it back and Edit -> EOL Conversion -> Convert to Windows Format.

Linux Script to check if process is running and act on the result

Programs to monitor if a process on a system is running.

Script is stored in crontab and runs once every minute.

This works with if process is not running or process is running multiple times:

#! /bin/bash

case "$(pidof amadeus.x86 | wc -w)" in

0)  echo "Restarting Amadeus:     $(date)" >> /var/log/amadeus.txt
    /etc/amadeus/amadeus.x86 &
    ;;
1)  # all ok
    ;;
*)  echo "Removed double Amadeus: $(date)" >> /var/log/amadeus.txt
    kill $(pidof amadeus.x86 | awk '{print $1}')
    ;;
esac

0 If process is not found, restart it.
1 If process is found, all ok.
* If process running 2 or more, kill the last.


A simpler version. This just test if process is running, and if not restart it.

It just tests the exit flag $? from the pidof program. It will be 0 of process is running and 1 if not.

#!/bin/bash
pidof  amadeus.x86 >/dev/null
if [[ $? -ne 0 ]] ; then
        echo "Restarting Amadeus:     $(date)" >> /var/log/amadeus.txt
        /etc/amadeus/amadeus.x86 &
fi

And at last, a one liner

pidof amadeus.x86 >/dev/null ; [[ $? -ne 0 ]] && echo "Restarting Amadeus:     $(date)" >> /var/log/amadeus.txt && /etc/amadeus/amadeus.x86 &

cccam oscam

Where can I download mysql jdbc jar from?

Here's a one-liner using Maven:

mvn dependency:get -Dartifact=mysql:mysql-connector-java:5.1.38

Then, with default settings, it's available in:

$HOME/.m2/repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar

Just replace the version number if you need a different one.

How to generate random number in Bash?

I like this trick:

echo ${RANDOM:0:1} # random number between 1 and 9
echo ${RANDOM:0:2} # random number between 1 and 99

...

javascript pushing element at the beginning of an array

Use .unshift() to add to the beginning of an array.

TheArray.unshift(TheNewObject);

See MDN for doc on unshift() and here for doc on other array methods.

FYI, just like there's .push() and .pop() for the end of the array, there's .shift() and .unshift() for the beginning of the array.

Split a string by a delimiter in python

You can use the str.split method: string.split('__')

>>> "MATCHES__STRING".split("__")
['MATCHES', 'STRING']

How to specify credentials when connecting to boto3 S3?

There are numerous ways to store credentials while still using boto3.resource(). I'm using the AWS CLI method myself. It works perfectly.

https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html?fbclid=IwAR2LlrS4O2gYH6xAF4QDVIH2Q2tzfF_VZ6loM3XfXsPAOR4qA-pX_qAILys

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

There were (at time of posting) one or two little typos in the accepted answer above, so here's the cleaned up version. In this example I'm stopping the CPU profiler when receiving Ctrl+C.

// capture ctrl+c and stop CPU profiler                            
c := make(chan os.Signal, 1)                                       
signal.Notify(c, os.Interrupt)                                     
go func() {                                                        
  for sig := range c {                                             
    log.Printf("captured %v, stopping profiler and exiting..", sig)
    pprof.StopCPUProfile()                                         
    os.Exit(1)                                                     
  }                                                                
}()    

Sorting objects by property values

With ES6 arrow functions it will be like this:

//Let's say we have these cars
let cars = [ { brand: 'Porsche', top_speed: 260 },
  { brand: 'Benz', top_speed: 110 },
  { brand: 'Fiat', top_speed: 90 },
  { brand: 'Aston Martin', top_speed: 70 } ]

Array.prototype.sort() can accept a comparator function (here I used arrow notation, but ordinary functions work the same):

let sortedByBrand = [...cars].sort((first, second) => first.brand > second.brand)

// [ { brand: 'Aston Martin', top_speed: 70 },
//   { brand: 'Benz', top_speed: 110 },
//   { brand: 'Fiat', top_speed: 90 },
//   { brand: 'Porsche', top_speed: 260 } ]

The above approach copies the contents of cars array into a new one and sorts it alphabetically based on brand names. Similarly, you can pass a different function:

let sortedBySpeed =[...cars].sort((first, second) => first.top_speed > second.top_speed)

//[ { brand: 'Aston Martin', top_speed: 70 },
//  { brand: 'Fiat', top_speed: 90 },
//  { brand: 'Benz', top_speed: 110 },
//  { brand: 'Porsche', top_speed: 260 } ]

If you don't mind mutating the orginal array cars.sort(comparatorFunction) will do the trick.

regex for zip-code

^\d{5}(?:[-\s]\d{4})?$
  • ^ = Start of the string.
  • \d{5} = Match 5 digits (for condition 1, 2, 3)
  • (?:…) = Grouping
  • [-\s] = Match a space (for condition 3) or a hyphen (for condition 2)
  • \d{4} = Match 4 digits (for condition 2, 3)
  • …? = The pattern before it is optional (for condition 1)
  • $ = End of the string.

How to get response from S3 getObject in Node.js?

When doing a getObject() from the S3 API, per the docs the contents of your file are located in the Body property, which you can see from your sample output. You should have code that looks something like the following

const aws = require('aws-sdk');
const s3 = new aws.S3(); // Pass in opts to S3 if necessary

var getParams = {
    Bucket: 'abc', // your bucket name,
    Key: 'abc.txt' // path to the object you're looking for
}

s3.getObject(getParams, function(err, data) {
    // Handle any error and exit
    if (err)
        return err;

  // No error happened
  // Convert Body from a Buffer to a String

  let objectData = data.Body.toString('utf-8'); // Use the encoding necessary
});

You may not need to create a new buffer from the data.Body object but if you need you can use the sample above to achieve that.

how to store Image as blob in Sqlite & how to retrieve it?

byte[] byteArray = rs.getBytes("columnname");  

Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0 ,byteArray.length);

What is Persistence Context?

In layman terms we can say that Persistence Context is an environment where entities are managed, i.e it syncs "Entity" with the database.

android listview get selected item

final ListView lv = (ListView) findViewById(R.id.ListView01);

lv.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
        String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));

      }                 
});

I hope this fixes your problem.

TypeScript sorting an array

I wrote this one today while trying to recreate _.sortBy in TypeScript, and thought I would leave it for anyone in need.

// ** Credits for getKeyValue at the bottom **
export const getKeyValue = <T extends {}, U extends keyof T>(key: U) => (obj: T) => obj[key] 

export const sortBy = <T extends {}>(index: string, list: T[]): T[] => {
    return list.sort((a, b): number => {
        const _a = getKeyValue<keyof T, T>(index)(a)
        const _b = getKeyValue<keyof T, T>(index)(b)
        if (_a < _b) return -1
        if (_a > _b) return 1
        return 0
    })
}

Usage:

It expects an array of generic type T, hence the cast for <T extends {}>, as well as typing the parameter and function return type with T[]

const x = [{ label: 'anything' }, { label: 'goes'}]
const sorted = sortBy('label', x)

** getByKey fn found here

In Rails, how do you render JSON using a view?

RABL is probably the nicest solution to this that I've seen if you're looking for a cleaner alternative to ERb syntax. json_builder and argonaut, which are other solutions, both seem somewhat outdated and won't work with Rails 3.1 without some patching.

RABL is available via a gem or check out the GitHub repository; good examples too

https://github.com/nesquena/rabl

How can I style an Android Switch?

You can define the drawables that are used for the background, and the switcher part like this:

<Switch
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:thumb="@drawable/switch_thumb"
    android:track="@drawable/switch_bg" />

Now you need to create a selector that defines the different states for the switcher drawable. Here the copies from the Android sources:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/switch_thumb_disabled_holo_light" />
    <item android:state_pressed="true"  android:drawable="@drawable/switch_thumb_pressed_holo_light" />
    <item android:state_checked="true"  android:drawable="@drawable/switch_thumb_activated_holo_light" />
    <item                               android:drawable="@drawable/switch_thumb_holo_light" />
</selector>

This defines the thumb drawable, the image that is moved over the background. There are four ninepatch images used for the slider:

The deactivated version (xhdpi version that Android is using)The deactivated version
The pressed slider: The pressed slider
The activated slider (on state):The activated slider
The default version (off state): enter image description here

There are also three different states for the background that are defined in the following selector:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/switch_bg_disabled_holo_dark" />
    <item android:state_focused="true"  android:drawable="@drawable/switch_bg_focused_holo_dark" />
    <item                               android:drawable="@drawable/switch_bg_holo_dark" />
</selector>

The deactivated version: The deactivated version
The focused version: The focused version
And the default version:the default version

To have a styled switch just create this two selectors, set them to your Switch View and then change the seven images to your desired style.

How to PUT a json object with an array using curl

Your command line should have a -d/--data inserted before the string you want to send in the PUT, and you want to set the Content-Type and not Accept.

curl -H 'Content-Type: application/json' -X PUT -d '[JSON]' \
     http://example.com/service

Using the exact JSON data from the question, the full command line would become:

curl -H 'Content-Type: application/json' -X PUT \
    -d '{"tags":["tag1","tag2"],
         "question":"Which band?",
         "answers":[{"id":"a0","answer":"Answer1"},
                    {"id":"a1","answer":"answer2"}]}' \
    http://example.com/service

Note: JSON data wrapped only for readability, not valid for curl request.

How to create cron job using PHP?

This is the best explanation with code in PHP I have found so far:

http://code.tutsplus.com/tutorials/managing-cron-jobs-with-php--net-19428

In short:

Although the syntax of scheduling a new job may seem daunting at first glance, it's actually relatively simple to understand once you break it down. A cron job will always have five columns each of which represent a chronological 'operator' followed by the full path and command to execute:

* * * * * home/path/to/command/the_command.sh

Each of the chronological columns has a specific relevance to the schedule of the task. They are as follows:

Minutes represents the minutes of a given hour, 0-59 respectively.
Hours represents the hours of a given day, 0-23 respectively.
Days represents the days of a given month, 1-31 respectively.
Months represents the months of a given year, 1-12 respectively.
Day of the Week represents the day of the week, Sunday through Saturday, numerically, as 0-6 respectively.

enter image description here

So, for example, if one wanted to schedule a task for 12am on the first day of every month it would look something like this:

0 0 1 * * home/path/to/command/the_command.sh

If we wanted to schedule a task to run every Saturday at 8:30am we'd write it as follows:

30 8 * * 6 home/path/to/command/the_command.sh

There are also a number of operators which can be used to customize the schedule even further:

Commas is used to create a comma separated list of values for any of the cron columns.
Dashes is used to specify a range of values.
Asterisksis used to specify 'all' or 'every' value

Visit the link for the full article, it explains:

  1. What is the format of the cronjob if you want to enter/edit it manually.
  2. How to use PHP with SSH2 library to authenticate as the user, which crontab you are going to edit.
  3. Full PHP class with all necessary methods for authentication, editing and deleting crontab entries.

Create a table without a header in Markdown

At least for the GitHub Flavoured Markdown, you can give the illusion by making all the non-header row entries bold with the regular __ or ** formatting:

|Regular | text | in header | turns bold |
|-|-|-|-|
| __So__ | __bold__ | __all__ | __table entries__ |
| __and__ | __it looks__ | __like a__ | __"headerless table"__ |

Mac zip compress without __MACOSX folder?

This command did it for me:

zip -r Target.zip Source -x "*.DS_Store"

Target.zip is the zip file to create. Source is the source file/folder to zip up. And the _x parameter specifies the file/folder to not include. If the above doesn't work for whatever reason, try this instead:

zip -r Target.zip Source -x "*.DS_Store" -x "__MACOSX"

Sending and Receiving SMS and MMS in Android (pre Kit Kat Android 4.4)

I dont understand the frustrations. Why not just make a broadcastreceiver that filters for this intent:

android.provider.Telephony.MMS_RECEIVED

I checked a little further and you might need system level access to get this (rooted phone).

Parse an HTML string with JS

EDIT: The solution below is only for HTML "fragments" since html,head and body are removed. I guess the solution for this question is DOMParser's parseFromString() method.


For HTML fragments, the solutions listed here works for most HTML, however for certain cases it won't work.

For example try parsing <td>Test</td>. This one won't work on the div.innerHTML solution nor DOMParser.prototype.parseFromString nor range.createContextualFragment solution. The td tag goes missing and only the text remains.

Only jQuery handles that case well.

So the future solution (MS Edge 13+) is to use template tag:

function parseHTML(html) {
    var t = document.createElement('template');
    t.innerHTML = html;
    return t.content.cloneNode(true);
}

var documentFragment = parseHTML('<td>Test</td>');

For older browsers I have extracted jQuery's parseHTML() method into an independent gist - https://gist.github.com/Munawwar/6e6362dbdf77c7865a99

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

/*?????? ??????? ? ??????*/
char* replace_char(char* str, char in, char out) {
    char * p = str;

    while(p != '\0') {
        if(*p == in)
            *p == out;
        ++p;
    }

    return str;
}

How to convert password into md5 in jquery?

Fiddle: http://jsfiddle.net/33HMj/

Js:

var md5 = function(value) {
    return CryptoJS.MD5(value).toString();
}

$("input").keyup(function () {
     var value = $(this).val(),
         hash = md5(value);
     $(".test").html(hash);
 });

Print Html template in Angular 2 (ng-print in Angular 2)

In case anyone else comes across this problem, if you have already laid the page out, I would recommend using media queries to set up your print page. You can then simply attach a print function to your html button and in your component call window.print();

component.html:

<div class="doNotPrint">
    Header is here.
</div>

<div>
    all my beautiful print-related material is here.
</div>

<div class="doNotPrint">
    my footer is here.
    <button (click)="onPrint()">Print</button>
</div>

component.ts:

onPrint(){
    window.print();
}

component.css:

@media print{
  .doNotPrint{display:none !important;}
}

You can optionally also add other elements / sections you do not wish to print in the media query.

You can change the document margins and all in the print query as well, which makes it quite powerful. There are many articles online. Here is one that seems comprehensive: https://www.sitepoint.com/create-a-customized-print-stylesheet-in-minutes/ It also means you don't have to create a separate script to create a 'print version' of the page or use lots of javascript.

Android: why is there no maxHeight for a View?

if you guys want to make a non-overflow scrollview or listview, just but it on a RelativeLayout with a topview and bottomview on top and bottom for it:

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/topview"
    android:layout_below="@+id/bottomview" >

How to format current time using a yyyyMMddHHmmss format?

This question comes in top of Google search when you find "golang current time format" so, for all the people that want to use another format, remember that you can always call to:

t := time.Now()

t.Year()

t.Month()

t.Day()

t.Hour()

t.Minute()

t.Second()

For example, to get current date time as "YYYY-MM-DDTHH:MM:SS" (for example 2019-01-22T12:40:55) you can use these methods with fmt.Sprintf:

t := time.Now()
formatted := fmt.Sprintf("%d-%02d-%02dT%02d:%02d:%02d",
        t.Year(), t.Month(), t.Day(),
        t.Hour(), t.Minute(), t.Second())

As always, remember that docs are the best source of learning: https://golang.org/pkg/time/

In Perl, how can I read an entire file into a string?

Another possible way:

open my $fh, '<', "filename";
read $fh, my $string, -s $fh;
close $fh;

Is it correct to use DIV inside FORM?

Definition and Usage

The tag defines a division or a section in an HTML document.

The tag is used to group block-elements to format them with styles. http://www.w3schools.com/tags/tag_div.asp

Also DIV - MDN

The HTML element (or HTML Document Division Element) is the generic container for flow content, which does not inherently represent anything. It can be used to group elements for styling purposes (using the class or id attributes), or because they share attribute values, such as lang. It should be used only when no other semantic element (such as or ) is appropriate.

You can use div inside form, if you are talking about using div instead of table, then google about Tableless web design

How to do a JUnit assert on a message in a logger

Here is what i did for logback.

I created a TestAppender class:

public class TestAppender extends AppenderBase<ILoggingEvent> {

    private Stack<ILoggingEvent> events = new Stack<ILoggingEvent>();

    @Override
    protected void append(ILoggingEvent event) {
        events.add(event);
    }

    public void clear() {
        events.clear();
    }

    public ILoggingEvent getLastEvent() {
        return events.pop();
    }
}

Then in the parent of my testng unit test class I created a method:

protected TestAppender testAppender;

@BeforeClass
public void setupLogsForTesting() {
    Logger root = (Logger)LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    testAppender = (TestAppender)root.getAppender("TEST");
    if (testAppender != null) {
        testAppender.clear();
    }
}

I have a logback-test.xml file defined in src/test/resources and I added a test appender:

<appender name="TEST" class="com.intuit.icn.TestAppender">
    <encoder>
        <pattern>%m%n</pattern>
    </encoder>
</appender>

and added this appender to the root appender:

<root>
    <level value="error" />
    <appender-ref ref="STDOUT" />
    <appender-ref ref="TEST" />
</root>

Now in my test classes that extend from my parent test class I can get the appender and get the last message logged and verify the message, the level, the throwable.

ILoggingEvent lastEvent = testAppender.getLastEvent();
assertEquals(lastEvent.getMessage(), "...");
assertEquals(lastEvent.getLevel(), Level.WARN);
assertEquals(lastEvent.getThrowableProxy().getMessage(), "...");

C++ Convert string (or char*) to wstring (or wchar_t*)

Your question is underspecified. Strictly, that example is a syntax error. However, mbstowcs is probably what you're looking for.

It is a C-library function and operates on buffers, but here's an easy-to-use idiom, courtesy of Mooing Duck:

std::wstring ws(s.size(), L' '); // Overestimate number of code points.
ws.resize(::mbstowcs_s(&ws[0], ws.size(), s.c_str(), s.size())); // Shrink to fit.

Raise an error manually in T-SQL to jump to BEGIN CATCH block

You're looking for RAISERROR.

From MSDN:

Generates an error message and initiates error processing for the session. RAISERROR can either reference a user-defined message stored in the sys.messages catalog view or build a message dynamically. The message is returned as a server error message to the calling application or to an associated CATCH block of a TRY…CATCH construct.

CodeProject has a good article that also describes in-depth the details of how it works and how to use it.

C#: HttpClient with POST parameters

As Ben said, you are POSTing your request ( HttpMethod.Post specified in your code )

The querystring (get) parameters included in your url probably will not do anything.

Try this:

string url = "http://myserver/method";    
string content = "param1=1&param2=2";
HttpClientHandler handler = new HttpClientHandler();
HttpClient httpClient = new HttpClient(handler);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
HttpResponseMessage response = await httpClient.SendAsync(request,content);

HTH,

bovako

How to load image files with webpack file-loader

Regarding problem #1

Once you have the file-loader configured in the webpack.config, whenever you use import/require it tests the path against all loaders, and in case there is a match it passes the contents through that loader. In your case, it matched

{
    test: /\.(jpe?g|png|gif|svg)$/i, 
    loader: "file-loader?name=/public/icons/[name].[ext]"
}

// For newer versions of Webpack it should be
{
    test: /\.(jpe?g|png|gif|svg)$/i, 
    loader: 'file-loader',
    options: {
      name: '/public/icons/[name].[ext]'
    }
}

and therefore you see the image emitted to

dist/public/icons/imageview_item_normal.png

which is the wanted behavior.

The reason you are also getting the hash file name, is because you are adding an additional inline file-loader. You are importing the image as:

'file!../../public/icons/imageview_item_normal.png'.

Prefixing with file!, passes the file into the file-loader again, and this time it doesn't have the name configuration.

So your import should really just be:

import img from '../../public/icons/imageview_item_normal.png'

Update

As noted by @cgatian, if you actually want to use an inline file-loader, ignoring the webpack global configuration, you can prefix the import with two exclamation marks (!!):

import '!!file!../../public/icons/imageview_item_normal.png'.

Regarding problem #2

After importing the png, the img variable only holds the path the file-loader "knows about", which is public/icons/[name].[ext] (aka "file-loader? name=/public/icons/[name].[ext]"). Your output dir "dist" is unknown. You could solve this in two ways:

  1. Run all your code under the "dist" folder
  2. Add publicPath property to your output config, that points to your output directory (in your case ./dist).

Example:

output: {
  path: PATHS.build,
  filename: 'app.bundle.js',
  publicPath: PATHS.build
},

Eclipse internal error while initializing Java tooling

Just change the following values at "eclipse.ini" file to the following:

-Xms1024m
-Xmx2048m

Note:

  • You can find the "eclipse.ini" file by right click eclipse icon on and select "Open file location".
  • This error occurs because the eclipse is running out of memory, so we just increased the assigned memory for the eclipse application.

error C2039: 'string' : is not a member of 'std', header file problem

You need to have

#include <string>

in the header file too.The forward declaration on it's own doesn't do enough.

Also strongly consider header guards for your header files to avoid possible future problems as your project grows. So at the top do something like:

#ifndef THE_FILE_NAME_H
#define THE_FILE_NAME_H

/* header goes in here */

#endif

This will prevent the header file from being #included multiple times, if you don't have such a guard then you can have issues with multiple declarations.

How to check if file already exists in the folder

'In Visual Basic

Dim FileName = "newfile.xml" ' The Name of file with its Extension Example A.txt or A.xml

Dim FilePath ="C:\MyFolderName" & "\" & FileName  'First Name of Directory and Then Name of Folder if it exists and then attach the name of file you want to search.

If System.IO.File.Exists(FilePath) Then
    MsgBox("The file exists")
Else
    MsgBox("the file doesn't exist")
End If

Given an array of numbers, return array of products of all other numbers (no division)

Try this!

import java.util.*;
class arrProduct
{
 public static void main(String args[])
     {
         //getting the size of the array
         Scanner s = new Scanner(System.in);
            int noe = s.nextInt();

        int out[]=new int[noe];
         int arr[] = new int[noe];

         // getting the input array
         for(int k=0;k<noe;k++)
         {
             arr[k]=s.nextInt();
         }

         int val1 = 1,val2=1;
         for(int i=0;i<noe;i++)
         {
             int res=1;

                 for(int j=1;j<noe;j++)
                 {
                if((i+j)>(noe-1))
                {

                    int diff = (i+j)-(noe);

                    if(arr[diff]!=0)
                    {
                    res = res * arr[diff];
                    }
                }

                else
                {
                    if(arr[i+j]!=0)
                    {
                    res= res*arr[i+j];
                    }
                }


             out[i]=res;

         }
         }

         //printing result
         System.out.print("Array of Product: [");
         for(int l=0;l<out.length;l++)
         {
             if(l!=out.length-1)
             {
            System.out.print(out[l]+",");
             }
             else
             {
                 System.out.print(out[l]);
             }
         }
         System.out.print("]");
     }

}

Is there a decorator to simply cache function return values?

If you are using Django Framework, it has such a property to cache a view or response of API's using @cache_page(time) and there can be other options as well.

Example:

@cache_page(60 * 15, cache="special_cache")
def my_view(request):
    ...

More details can be found here.

Watch multiple $scope attributes

how about:

scope.$watch(function() { 
   return { 
      a: thing-one, 
      b: thing-two, 
      c: red-fish, 
      d: blue-fish 
   }; 
}, listener...);

How to get body of a POST in php?

A possible reason for an empty $_POST is that the request is not POST, or not POST anymore... It may have started out as post, but encountered a 301 or 302 redirect somewhere, which is switched to GET!

Inspect $_SERVER['REQUEST_METHOD'] to check if this is the case.

See https://stackoverflow.com/a/19422232/109787 for a good discussion of why this should not happen but still does.

c# open a new form then close the current form?

I think this is much easier :)

    private void btnLogin_Click(object sender, EventArgs e)
    {
        //this.Hide();
        //var mm = new MainMenu();
        //mm.FormClosed += (s, args) => this.Close();
        //mm.Show();

        this.Hide();
        MainMenu mm = new MainMenu();
        mm.Show();

    }

Export tables to an excel spreadsheet in same directory

For people who find this via search engines, you do not need VBA. You can just:

1.) select the query or table with your mouse
2.) click export data from the ribbon
3.) click excel from the export subgroup
4.) follow the wizard to select the output file and location.

how to print an exception using logger?

Try to log the stack trace like below:

logger.error("Exception :: " , e);

How to find the kth largest element in an unsorted array of length n in O(n)?

it is similar to the quickSort strategy, where we pick an arbitrary pivot, and bring the smaller elements to its left, and the larger to the right

    public static int kthElInUnsortedList(List<int> list, int k)
    {
        if (list.Count == 1)
            return list[0];

        List<int> left = new List<int>();
        List<int> right = new List<int>();

        int pivotIndex = list.Count / 2;
        int pivot = list[pivotIndex]; //arbitrary

        for (int i = 0; i < list.Count && i != pivotIndex; i++)
        {
            int currentEl = list[i];
            if (currentEl < pivot)
                left.Add(currentEl);
            else
                right.Add(currentEl);
        }

        if (k == left.Count + 1)
            return pivot;

        if (left.Count < k)
            return kthElInUnsortedList(right, k - left.Count - 1);
        else
            return kthElInUnsortedList(left, k);
    }

Find out how much memory is being used by an object in Python

Try this:

sys.getsizeof(object)

getsizeof() Return the size of an object in bytes. It calls the object’s __sizeof__ method and adds an additional garbage collector overhead if the object is managed by the garbage collector.

A recursive recipe

concatenate two database columns into one resultset column

If both Column are numeric Then Use This code

Just Cast Column As Varchar(Size)

Example:

Select (Cast(Col1 as Varchar(20)) + '-' + Cast(Col2 as Varchar(20))) As Col3 from Table

SHA-1 fingerprint of keystore certificate

As of Sept 2020, if you want to get the SHA-1 fingerprint of keystore certificate of Release. Simply open up your Google Play Developer Console and open the App Signing tab.

enter image description here

How do I find a default constraint using INFORMATION_SCHEMA?

select c.name, col.name from sys.default_constraints c
    inner join sys.columns col on col.default_object_id = c.object_id
    inner join sys.objects o  on o.object_id = c.parent_object_id
    inner join sys.schemas s on s.schema_id = o.schema_id
where s.name = @SchemaName and o.name = @TableName and col.name = @ColumnName

Div vertical scrollbar show

Always : If you always want vertical scrollbar, use overflow-y: scroll;

jsFiddle:

<div style="overflow-y: scroll;">
......
</div>

When needed: If you only want vertical scrollbar when needed, use overflow-y: auto; (You need to specify a height in this case)

jsFiddle:

<div style="overflow-y: auto; height:150px; ">
....
</div>

Change background position with jQuery

rebellion's answer above won't actually work, because to CSS, 'background-position' is actually shorthand for 'background-position-x' and 'background-position-y' so the correct version of his code would be:

$(document).ready(function(){
    $('#submenu li').hover(function(){
        $('#carousel').css('background-position-x', newValueX);
        $('#carousel').css('background-position-y', newValue);
    }, function(){
        $('#carousel').css('background-position-x', oldValueX);
        $('#carousel').css('background-position-y', oldValueY);
    });
});

It took about 4 hours of banging my head against it to come to that aggravating realization.

The EXECUTE permission was denied on the object 'xxxxxxx', database 'zzzzzzz', schema 'dbo'

you need to run something like this

GRANT Execute ON [dbo].fnc_whatEver TO [domain\user]

Redirect within component Angular 2

This worked for me Angular cli 6.x:

import {Router} from '@angular/router';

constructor(private artistService: ArtistService, private router: Router) { }

  selectRow(id: number): void{
       this.router.navigate([`./artist-detail/${id}`]);

  }

Conditional step/stage in Jenkins pipeline

Just use if and env.BRANCH_NAME, example:

    if (env.BRANCH_NAME == "deployment") {                                          
        ... do some build ...
    } else {                                   
        ... do something else ...
    }                                                                       

Comparing strings, c++

string cat = "cat";
string human = "human";

cout << cat.compare(human) << endl; 

This code will give -1 as a result. This is due to the first non-matching character of the compared string 'h' is lower or appears after 'c' in alphabetical order, even though the compared string, 'human' is longer than 'cat'.

I find the return value described in cplusplus.com is more accurate which are-:

0 : They compare equal

<0 : Either the value of the first character that does not match is lower in the compared string, or all compared characters match but the compared string is shorter.

more than 0 : Either the value of the first character that does not match is greater in the compared string, or all compared characters match but the compared string is longer.

Moreover, IMO cppreference.com's description is simpler and so far best describe to my own experience.

negative value if *this appears before the character sequence specified by the arguments, in lexicographical order

zero if both character sequences compare equivalent

positive value if *this appears after the character sequence specified by the arguments, in lexicographical order

How to export non-exportable private key from store

You might need to uninstall antivirus (in my case I had to get rid of Avast).

This makes sure that crypto::cng command will work. Otherwise it was giving me errors:

mimikatz $ crypto::cng
ERROR kull_m_patch_genericProcessOrServiceFromBuild ; OpenProcess (0x00000005)

After removing Avast:

mimikatz $ crypto::cng
"KeyIso" service patched

Magic. (:

BTW

Windows Defender is another program blocking the program to work, so you will need also to disable it for the time of using program at least.

How to add an image to the emulator gallery in android studio?

I went through the Android Device Monitor

  1. Click on device
  2. Select Android Device Monitor's File Explorer tab
  3. Select Pictures folder (path: data -> media -> 0 -> Pictures)
  4. Click "Push folders on to device" icon
  5. Select pic from computer and ok.

Image re-size to 50% of original size in HTML

The percentage setting does not take into account the original image size. From w3schools :

In HTML 4.01, the width could be defined in pixels or in % of the containing element. In HTML5, the value must be in pixels.

Also, good practice advice from the same source :

Tip: Downsizing a large image with the height and width attributes forces a user to download the large image (even if it looks small on the page). To avoid this, rescale the image with a program before using it on a page.

send bold & italic text on telegram bot with html

To send bold:

  1. Set the parse_mode to markdown and send *bold*
  2. Set the parse_mode to html and send <b>bold</b>

To send italic:

  1. Set the parse_mode to markdown and send _italic_
  2. Set the parse_mode to html and send <i>italic</i>

How to change Git log date formats

Be aware of the "date=iso" format: it isn't exactly ISO 8601.
See commit "466fb67" from Beat Bolli (bbolli), for Git 2.2.0 (November 2014)

pretty: provide a strict ISO 8601 date format

Git's "ISO" date format does not really conform to the ISO 8601 standard due to small differences, and it cannot be parsed by ISO 8601-only parsers, e.g. those of XML toolchains.

The output from "--date=iso" deviates from ISO 8601 in these ways:

  • a space instead of the T date/time delimiter
  • a space between time and time zone
  • no colon between hours and minutes of the time zone

Add a strict ISO 8601 date format for displaying committer and author dates.
Use the '%aI' and '%cI' format specifiers and add '--date=iso-strict' or '--date=iso8601-strict' date format names.

See this thread for discussion.

React img tag issue with url and class

Remember that your img is not really a DOM element but a javascript expression.

  1. This is a JSX attribute expression. Put curly braces around the src string expression and it will work. See http://facebook.github.io/react/docs/jsx-in-depth.html#attribute-expressions

  2. In javascript, the class attribute is reference using className. See the note in this section: http://facebook.github.io/react/docs/jsx-in-depth.html#react-composite-components

    /** @jsx React.DOM */
    
    var Hello = React.createClass({
        render: function() {
            return <div><img src={'http://placehold.it/400x20&text=slide1'} alt="boohoo" className="img-responsive"/><span>Hello {this.props.name}</span></div>;
        }
    });
    
    React.renderComponent(<Hello name="World" />, document.body);
    

Maven Java EE Configuration Marker with Java Server Faces 1.2

The m2e plugin generate project configuration every time when you update project (Maven->Update Project ... That action overrides facets setting configured manually in Eclipse. Therefore you have to configure it on pom level. By setting properties in pom file you can tell m2e plugin what to do.

Enable/Disable the JAX-RS/JPA/JSF Configurators at the pom.xml level The optional JAX-RS, JPA and JSF configurators can be enabled or disabled at a workspace level from Window > Preferences > Maven > Java EE Integration. Now, you can have a finer grain control on these configurators directly from your pom.xml properties :

Adding false in your pom properties section will disable the JAX-RS configurator Adding false in your pom properties section will disable the JPA configurator Adding false in your pom properties section will disable the JSF configurator The pom settings always override the workspace preferences. So if you have, for instance the JPA configurator disabled at the workspace level, using true will enable it on your project anyway. (http://wiki.eclipse.org/M2E-WTP/New_and_Noteworthy/1.0.0)

What is PHPSESSID?

It's the identifier for your current session in PHP. If you delete it, you won't be able to access/make use of session variables. I'd suggest you keep it.

div inside table

You can't put a div directly inside a table, like this:

<!-- INVALID -->
<table>
  <div>
    Hello World
  </div>
</table>

Putting a div inside a td or th element is fine, however:

<!-- VALID -->
<table>
  <tr>
    <td>
      <div>
        Hello World
      </div>
    </td>
  </tr>
</table>

What does this thread join code mean?

Simply put:
t1.join() returns after t1 is completed.
It doesn't do anything to thread t1, except wait for it to finish.
Naturally, code following t1.join() will be executed only after t1.join() returns.

How to get the last element of a slice?

For just reading the last element of a slice:

sl[len(sl)-1]

For removing it:

sl = sl[:len(sl)-1]

See this page about slice tricks

If Else in LINQ

This might work...

from p in db.products
    select new
    {
        Owner = (p.price > 0 ?
            from q in db.Users select q.Name :
            from r in db.ExternalUsers select r.Name)
    }

Change Activity's theme programmatically

I have used this code to implement dark mode...it worked fine for me...You can use it in a switch on....listener...

//setting up Night Mode...
 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
//Store current mode in a sharedprefernce to retrieve on restarting app
            editor.putBoolean("NightMode", true);
            editor.apply();
//restart all the activities to apply changed mode...
            TaskStackBuilder.create(getActivity())
                    .addNextIntent(new Intent(getActivity(), MainActivity.class))
                    .addNextIntent(getActivity().getIntent())
                    .startActivities();

IIS w3svc error

Run cmd as administrator. Type iisreset. That's it.

The SELECT permission was denied on the object 'sysobjects', database 'mssqlsystemresource', schema 'sys'

In my case, simply giving the user permissions on the database fixed it.

So Right click on the database -> Click Properties -> [left hand menu] Click Permissions -> and scroll down to Backup database -> Tick "Grant"

Where can I find the Tomcat 7 installation folder on Linux AMI in Elastic Beanstalk?

My server is CentOS 7, and I install tomcat by:

sudo yum install tomcat
sudo yum install tomcat-webapps tomcat-admin-webapps

I found my webapps folders in:

/usr/share/tomcat/

and

/var/lib/tomcat/

Postgres ERROR: could not open file for reading: Permission denied

I resolved the same issue with a recursive chown on the parent folder:

sudo chown -R postgres:postgres /home/my_user/export_folder

(my export being in /home/my_user/export_folder/export_1.csv)

Convert base class to derived class

No it is not possible. The only way that is possible is

static void Main(string[] args)
{
    BaseClass myBaseObject = new DerivedClass();
    DerivedClass myDerivedObject = myBaseObject as DerivedClass;

    myDerivedObject.MyDerivedProperty = true;
}

How can I get the error message for the mail() function?

In my case, I couldn't get the error message in my PHP script no matter what I do (error_get_last(), or ini_set('display_errors',1);) don't show the error message

according to this post

The return value from $mail refers only to whether or not your server's mailing system accepted the message for delivery, and does not and can not in any way know whether or not you are providing valid arguments. For example, the return value would be false if sendmail failed to load (e.g. if it wasn't installed properly), but would return true if sendmail loaded properly but the recipient address doesn't exist.

I confirm this because after some failed attempts to use mail() in my PHP scripts, it turns that sendmail was not installed on my machine, however the php.ini variable sendmail_path was /usr/sbin/sendmail -t -i

1- I installed sendmail from my package manager shell> dnf install sendmail

2- I started it shell> service sendmail start

3- Now if any PHP mail() function fails I find the errors of the sendmail program logged under /var/mail/ directory. 1 file per user

For example this snippet is taken from my /var/mail/root file

The original message was received at Sun, 29 Jul 2018 22:37:51 +0200
from localhost [127.0.0.1]
   ----- The following addresses had permanent fatal errors -----
<[email protected]>
    (reason: 550 Host unknown)

My system is linux Fedora 28 with apache2.4 and PHP 7.2

How to split a string at the first `/` (slash) and surround part of it in a `<span>`?

use this

<div id="date">23/05/2013</div>
<script type="text/javascript">
$(document).ready(function(){
  var x = $("#date").text();
    x.text(x.substring(0, 2) + '<br />'+x.substring(3));     
});
</script>

HashMap(key: String, value: ArrayList) returns an Object instead of ArrayList?

The get method of the HashMap is returning an Object, but the variable current is expected to take a ArrayList:

ArrayList current = new ArrayList();
// ...
current = dictMap.get(dictCode);

For the above code to work, the Object must be cast to an ArrayList:

ArrayList current = new ArrayList();
// ...
current = (ArrayList)dictMap.get(dictCode);

However, probably the better way would be to use generic collection objects in the first place:

HashMap<String, ArrayList<Object>> dictMap =
    new HashMap<String, ArrayList<Object>>();

// Populate the HashMap.

ArrayList<Object> current = new ArrayList<Object>();      
if(dictMap.containsKey(dictCode)) {
    current = dictMap.get(dictCode);   
}

The above code is assuming that the ArrayList has a list of Objects, and that should be changed as necessary.

For more information on generics, The Java Tutorials has a lesson on generics.

How to create full compressed tar file using Python?

Previous answers advise using the tarfile Python module for creating a .tar.gz file in Python. That's obviously a good and Python-style solution, but it has serious drawback in speed of the archiving. This question mentions that tarfile is approximately two times slower than the tar utility in Linux. According to my experience this estimation is pretty correct.

So for faster archiving you can use the tar command using subprocess module:

subprocess.call(['tar', '-czf', output_filename, file_to_archive])

How to create my json string by using C#?

The json is kind of odd, it's like the students are properties of the "GetQuestion" object, it should be easy to be a List.....

About the libraries you could use are.

And there could be many more, but that are what I've used

About the json I don't now maybe something like this

public class GetQuestions
{
    public List<Student> Questions { get; set; }
}

public class Student
{
    public string Code { get; set; }
    public string Questions { get; set; }
}

void Main()
{
    var gq = new GetQuestions
    {
        Questions = new List<Student>
        {
            new Student {Code = "s1", Questions = "Q1,Q2"},
            new Student {Code = "s2", Questions = "Q1,Q2,Q3"},
            new Student {Code = "s3", Questions = "Q1,Q2,Q4"},
            new Student {Code = "s4", Questions = "Q1,Q2,Q5"},
        }
    };

    //Using Newtonsoft.json. Dump is an extension method of [Linqpad][4]
    JsonConvert.SerializeObject(gq).Dump();
}

Linqpad

and the result is this

{
     "Questions":[
        {"Code":"s1","Questions":"Q1,Q2"},
        {"Code":"s2","Questions":"Q1,Q2,Q3"},
        {"Code":"s3","Questions":"Q1,Q2,Q4"},
        {"Code":"s4","Questions":"Q1,Q2,Q5"}
      ]
 }

Yes I know the json is different, but the json that you want with dictionary.

void Main()
{
    var f = new Foo
    {
        GetQuestions = new Dictionary<string, string>
                {
                    {"s1", "Q1,Q2"},
                    {"s2", "Q1,Q2,Q3"},
                    {"s3", "Q1,Q2,Q4"},
                    {"s4", "Q1,Q2,Q4,Q6"},
                }
    };

    JsonConvert.SerializeObject(f).Dump();
}

class Foo
{
    public Dictionary<string, string> GetQuestions { get; set; }
}

And with Dictionary is as you want it.....

{
      "GetQuestions":
       {
              "s1":"Q1,Q2",
              "s2":"Q1,Q2,Q3",
              "s3":"Q1,Q2,Q4",
              "s4":"Q1,Q2,Q4,Q6"
       }
 }

Memory errors and list limits?

The MemoryError exception that you are seeing is the direct result of running out of available RAM. This could be caused by either the 2GB per program limit imposed by Windows (32bit programs), or lack of available RAM on your computer. (This link is to a previous question).

You should be able to extend the 2GB by using 64bit copy of Python, provided you are using a 64bit copy of windows.

The IndexError would be caused because Python hit the MemoryError exception before calculating the entire array. Again this is a memory issue.

To get around this problem you could try to use a 64bit copy of Python or better still find a way to write you results to file. To this end look at numpy's memory mapped arrays.

You should be able to run you entire set of calculation into one of these arrays as the actual data will be written disk, and only a small portion of it held in memory.

jQuery: select all elements of a given class, except for a particular Id

I'll just throw in a JS (ES6) answer, in case someone is looking for it:

Array.from(document.querySelectorAll(".myClass:not(#myId)")).forEach((el,i) => {
    doSomething(el);
}

Update (this may have been possible when I posted the original answer, but adding this now anyway):

document.querySelectorAll(".myClass:not(#myId)").forEach((el,i) => {
    doSomething(el);
});

This gets rid of the Array.from usage.

document.querySelectorAll returns a NodeList.
Read here to know more about how to iterate on it (and other things): https://developer.mozilla.org/en-US/docs/Web/API/NodeList

Merging two arrays in .NET

int [] SouceArray1 = new int[] {2,1,3};
int [] SourceArray2 = new int[] {4,5,6};
int [] targetArray = new int [SouceArray1.Length + SourceArray2.Length];
SouceArray1.CopyTo(targetArray,0);
SourceArray2.CopyTo(targetArray,SouceArray1.Length) ; 
foreach (int i in targetArray) Console.WriteLine(i + " ");  

Using the above code two Arrays can be easily merged.

How can I rollback a git repository to a specific commit?

Another way:

Checkout the branch you want to revert, then reset your local working copy back to the commit that you want to be the latest one on the remote server (everything after it will go bye-bye). To do this, in SourceTree, I right-clicked on the and selected "Reset BRANCHNAME to this commit".

Then navigate to your repository's local directory and run this command:

git -c diff.mnemonicprefix=false -c core.quotepath=false push -v -f -- tags REPOSITORY_NAME BRANCHNAME:BRANCHNAME 

This will erase all commits after the current one in your local repository but only for that one branch.

Classes vs. Functions

It depends on the scenario. If you only want to compute the age of a person, then use a function since you want to implement a single specific behaviour.

But if you want to create an object, that contains the date of birth of a person (and possibly other data), allows to modify it, then computing the age could be one of many operations related to the person and it would be sensible to use a class instead.

Classes provide a way to merge together some data and related operations. If you have only one operation on the data then using a function and passing the data as argument you will obtain an equivalent behaviour, with less complex code.

Note that a class of the kind:

class A(object):
    def __init__(self, ...):
        #initialize
    def a_single_method(self, ...):
        #do stuff

isn't really a class, it is only a (complicated)function. A legitimate class should always have at least two methods(without counting __init__).

How to recover corrupted Eclipse workspace?

Remove a file with .dat extension in workspace/.metadata/.plugins/org.eclipse.wst.jsdt.core/ and then close eand open eclipse, maybe you cannot close eclipse, force it, with pkill -f eclipse if you are on linux or similar.

This solution avoid to import all of existents projects.

How to insert logo with the title of a HTML page?

Are you referring to the favicon?

Upload a 16x16px ico to your site, and link it in your head section.

<link rel="shortcut icon" href="/favicon.ico" />

There are a multitude of sites that help you convert images into .ico format too. This is just the first one I saw on Google. http://www.favicon.cc/

Python, creating objects

Create a class and give it an __init__ method:

class Student:
    def __init__(self, name, age, major):
        self.name = name
        self.age = age
        self.major = major

    def is_old(self):
        return self.age > 100

Now, you can initialize an instance of the Student class:

>>> s = Student('John', 88, None)
>>> s.name
    'John'
>>> s.age
    88

Although I'm not sure why you need a make_student student function if it does the same thing as Student.__init__.

Get HTML5 localStorage keys

We can also read by the name.

Say we have saved the value with name 'user' like this

localStorage.setItem('user', user_Detail);

Then we can read it by using

localStorage.getItem('user');

I used it and it is working smooth, no need to do the for loop

dynamically set iframe src

You should also consider that in some Opera versions onload is fired several times and add some hooks:

// fixing Opera 9.26, 10.00
if (doc.readyState && doc.readyState != 'complete') {
    // Opera fires load event multiple times
    // Even when the DOM is not ready yet
    // this fix should not affect other browsers
    return;
}

// fixing Opera 9.64
if (doc.body && doc.body.innerHTML == "false") {
    // In Opera 9.64 event was fired second time
    // when body.innerHTML changed from false
    // to server response approx. after 1 sec
    return;
}

Code borrowed from Ajax Upload

How to connect to mysql with laravel?

Maybe you forgot to first create a table migrations:

php artisan migrate:install

Also there is a very userful package Generators, which makes a lot of work for you https://github.com/JeffreyWay/Laravel-4-Generators#views

git submodule tracking latest

Edit (2020.12.28): GitHub change default master branch to main branch since October 2020. See https://github.com/github/renaming


Update March 2013

Git 1.8.2 added the possibility to track branches.

"git submodule" started learning a new mode to integrate with the tip of the remote branch (as opposed to integrating with the commit recorded in the superproject's gitlink).

# add submodule to track master branch
git submodule add -b master [URL to Git repo];

# update your submodule
git submodule update --remote 

If you had a submodule already present you now wish would track a branch, see "how to make an existing submodule track a branch".

Also see Vogella's tutorial on submodules for general information on submodules.

Note:

git submodule add -b . [URL to Git repo];
                    ^^^

See git submodule man page:

A special value of . is used to indicate that the name of the branch in the submodule should be the same name as the current branch in the current repository.


See commit b928922727d6691a3bdc28160f93f25712c565f6:

submodule add: If --branch is given, record it in .gitmodules

This allows you to easily record a submodule.<name>.branch option in .gitmodules when you add a new submodule. With this patch,

$ git submodule add -b <branch> <repository> [<path>]
$ git config -f .gitmodules submodule.<path>.branch <branch>

reduces to

$ git submodule add -b <branch> <repository> [<path>]

This means that future calls to

$ git submodule update --remote ...

will get updates from the same branch that you used to initialize the submodule, which is usually what you want.

Signed-off-by: W. Trevor King [email protected]


Original answer (February 2012):

A submodule is a single commit referenced by a parent repo.
Since it is a Git repo on its own, the "history of all commits" is accessible through a git log within that submodule.

So for a parent to track automatically the latest commit of a given branch of a submodule, it would need to:

  • cd in the submodule
  • git fetch/pull to make sure it has the latest commits on the right branch
  • cd back in the parent repo
  • add and commit in order to record the new commit of the submodule.

gitslave (that you already looked at) seems to be the best fit, including for the commit operation.

It is a little annoying to make changes to the submodule due to the requirement to check out onto the correct submodule branch, make the change, commit, and then go into the superproject and commit the commit (or at least record the new location of the submodule).

Other alternatives are detailed here.

Python convert set to string and vice versa

If you do not need the serialized text to be human readable, you can use pickle.

import pickle

s = set([1,2,3])

serialized_s = pickle.dumps(s)
print "serialized:"
print serialized_s

deserialized_s = pickle.loads(serialized_s)
print "deserialized:"
print deserialized_s

Result:

serialized:
c__builtin__
set
p0
((lp1
I1
aI2
aI3
atp2
Rp3
.
deserialized:
set([1, 2, 3])

How to change the new TabLayout indicator color and height

With the desing support library v23 you can set programmatically the color and the height.

Just use for the height:

TabLayout.setSelectedTabIndicatorHeight(int height)

Here the official javadoc.

Just use for the color:

TabLayout.setSelectedTabIndicatorColor(int color)

Here the official javadoc.

Here you can find the info in the Google Tracker.

How to destroy a DOM element with jQuery?

If you want to completely destroy the target, you have a couple of options. First you can remove the object from the DOM as described above...

console.log($target);   // jQuery object
$target.remove();       // remove target from the DOM
console.log($target);   // $target still exists

Option 1 - Then replace target with an empty jQuery object (jQuery 1.4+)

$target = $();
console.log($target);   // empty jQuery object

Option 2 - Or delete the property entirely (will cause an error if you reference it elsewhere)

delete $target;
console.log($target);   // error: $target is not defined

More reading: info about empty jQuery object, and info about delete

Pandas - Get first row value of a given column

Another way to do this:

first_value = df['Btime'].values[0]

This way seems to be faster than using .iloc:

In [1]: %timeit -n 1000 df['Btime'].values[20]
5.82 µs ± 142 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [2]: %timeit -n 1000 df['Btime'].iloc[20]
29.2 µs ± 1.28 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Reading and writing environment variables in Python?

Use os.environ[str(DEBUSSY)] for both reading and writing (http://docs.python.org/library/os.html#os.environ).

As for reading, you have to parse the number from the string yourself of course.

Operation must use an updatable query. (Error 3073) Microsoft Access

In essence, while your SQL looks perfectly reasonable, Jet has never supported the SQL standard syntax for UPDATE. Instead, it uses its own proprietary syntax (different again from SQL Server's proprietary UPDATE syntax) which is very limited. Often, the only workarounds "Operation must use an updatable query" are very painful. Seriously consider switching to a more capable SQL product.

For some more details about your specific problems and some possible workarounds, see Update Query Based on Totals Query Fails.

How to show a running progress bar while page is loading

It’s a chicken-and-egg problem. You won’t be able to do it because you need to load the assets to display the progress bar widget, by which time your page will be either fully or partially downloaded. Also, you need to know the total size of the page prior to the user requesting in order to calculate a percentage.

It’s more hassle than it’s worth.

How can I scale an entire web page with CSS?

Jon Tan has done this with his site - http://jontangerine.com/ Everything including images has been declared in ems. Everything. This is how the desired effect is achieved. Text zoom and screen zoom yield almost the exact same result.

How do I initialize an empty array in C#?

Try this:

string[] a = new string[] { };

Check substring exists in a string in C

My own humble (case sensitive) solution:

uint8_t strContains(char* string, char* toFind)
{
    uint8_t slen = strlen(string);
    uint8_t tFlen = strlen(toFind);
    uint8_t found = 0;

    if( slen >= tFlen )
    {
        for(uint8_t s=0, t=0; s<slen; s++)
        {
            do{

                if( string[s] == toFind[t] )
                {
                    if( ++found == tFlen ) return 1;
                    s++;
                    t++;
                }
                else { s -= found; found=0; t=0; }

              }while(found);
        }
        return 0;
    }
    else return -1;
}

Results

strContains("this is my sample example", "th") // 1
strContains("this is my sample example", "sample") // 1
strContains("this is my sample example", "xam") // 1
strContains("this is my sample example", "ple") // 1
strContains("this is my sample example", "ssample") // 0
strContains("this is my sample example", "samplee") // 0
strContains("this is my sample example", "") // 0
strContains("str", "longer sentence") // -1
strContains("ssssssample", "sample") // 1
strContains("sample", "sample") // 1

Tested on ATmega328P (avr8-gnu-toolchain-3.5.4.1709) ;)

What does functools.wraps do?

As of python 3.5+:

@functools.wraps(f)
def g():
    pass

Is an alias for g = functools.update_wrapper(g, f). It does exactly three things:

  • it copies the __module__, __name__, __qualname__, __doc__, and __annotations__ attributes of f on g. This default list is in WRAPPER_ASSIGNMENTS, you can see it in the functools source.
  • it updates the __dict__ of g with all elements from f.__dict__. (see WRAPPER_UPDATES in the source)
  • it sets a new __wrapped__=f attribute on g

The consequence is that g appears as having the same name, docstring, module name, and signature than f. The only problem is that concerning the signature this is not actually true: it is just that inspect.signature follows wrapper chains by default. You can check it by using inspect.signature(g, follow_wrapped=False) as explained in the doc. This has annoying consequences:

  • the wrapper code will execute even when the provided arguments are invalid.
  • the wrapper code can not easily access an argument using its name, from the received *args, **kwargs. Indeed one would have to handle all cases (positional, keyword, default) and therefore to use something like Signature.bind().

Now there is a bit of confusion between functools.wraps and decorators, because a very frequent use case for developing decorators is to wrap functions. But both are completely independent concepts. If you're interested in understanding the difference, I implemented helper libraries for both: decopatch to write decorators easily, and makefun to provide a signature-preserving replacement for @wraps. Note that makefun relies on the same proven trick than the famous decorator library.

Resolving ORA-4031 "unable to allocate x bytes of shared memory"

All of the current answers are addressing the symptom (shared memory pool exhaustion), and not the problem, which is likely not using bind variables in your sql \ JDBC queries, even when it does not seem necessary to do so. Passing queries without bind variables causes Oracle to "hard parse" the query each time, determining its plan of execution, etc.

https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::p11_question_id:528893984337

Some snippets from the above link:

"Java supports bind variables, your developers must start using prepared statements and bind inputs into it. If you want your system to ultimately scale beyond say about 3 or 4 users -- you will do this right now (fix the code). It is not something to think about, it is something you MUST do. A side effect of this - your shared pool problems will pretty much disappear. That is the root cause. "

"The way the Oracle shared pool (a very important shared memory data structure) operates is predicated on developers using bind variables."

" Bind variables are SO MASSIVELY important -- I cannot in any way shape or form OVERSTATE their importance. "

How Do I Upload Eclipse Projects to GitHub?

Many of these answers mention how to share the project on Git, which is easy, you just share the code on git, but one thing to take note of is that there is no apparent "project file" that the end user can double click on. Instead you have to use Import->General->Existing project and select the whole folder

Best cross-browser method to capture CTRL+S with JQuery?

$(window).keypress(function(event) {
    if (!(event.which == 115 && event.ctrlKey) && !(event.which == 19)) return true;
    alert("Ctrl-S pressed");
    event.preventDefault();
    return false;
});

Key codes can differ between browsers, so you may need to check for more than just 115.

SQL - IF EXISTS UPDATE ELSE INSERT Syntax Error

In this approach only one statement is executed when the UPDATE is successful.

-- For each row in source
BEGIN TRAN    

UPDATE target
SET <target_columns> = <source_values>
WHERE <target_expression>

IF (@@ROWCOUNT = 0)
   INSERT target (<target_columns>)
VALUES (<source_values>)

COMMIT

The source was not found, but some or all event logs could not be searched

Inaccessible logs: Security

A new event source needs to have a unique name across all logs including Security (which needs admin privilege when it's being read).

So your app will need admin privilege to create a source. But that's probably an overkill.

I wrote this powershell script to create the event source at will. Save it as *.ps1 and run it with any privilege and it will elevate itself.

# CHECK OR RUN AS ADMIN

If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{   
    $arguments = "& '" + $myinvocation.mycommand.definition + "'"
    Start-Process powershell -Verb runAs -ArgumentList $arguments
    Break
}

# CHECK FOR EXISTENCE OR CREATE

$source = "My Service Event Source";
$logname = "Application";

if ([System.Diagnostics.EventLog]::SourceExists($source) -eq $false) {
    [System.Diagnostics.EventLog]::CreateEventSource($source, $logname);
    Write-Host $source -f white -nonewline; Write-Host " successfully added." -f green;
}
else
{
    Write-Host $source -f white -nonewline; Write-Host " already exists.";
}

# DONE

Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');

PHP Check for NULL

Make sure that the value of the column is really NULL and not an empty string or 0.

Warning: mysqli_query() expects parameter 1 to be mysqli, resource given

You are mixing mysqli and mysql extensions, which will not work.

You need to use

$myConnection= mysqli_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql"); 

mysqli_select_db($myConnection, "mrmagicadam") or die ("no database");   

mysqli has many improvements over the original mysql extension, so it is recommended that you use mysqli.

show all tables in DB2 using the LIST command

I'm using db2 7.1 and SQuirrel. This is the only query that worked for me.

select * from SYSIBM.tables where table_schema = 'my_schema' and table_type = 'BASE TABLE';

dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib

Switch to an older openssl package

brew switch openssl 1.0.2s

Or, depending on your exact system configuration, you may need to switch to a different version. Check the output of ls -al /usr/local/Cellar/openssl for the version number to switch to.

brew switch openssl 1.0.2q
# or
brew switch openssl 1.0.2r
# or 
brew switch openssl 1.0.2s
# or
brew switch openssl 1.0.2t
# etc...

MySQL - how to front pad zip code with "0"?

CHAR(5)

or

MEDIUMINT (5) UNSIGNED ZEROFILL

The first takes 5 bytes per zip code.

The second takes only 3 bytes per zip code. The ZEROFILL option is necessary for zip codes with leading zeros.

How to make a machine trust a self-signed Java application

SERIOUS DISCLAIMER

This solution has a serious security flaw. Please use at your own risk.
Have a look at the comments on this post, and look at all the answers to this question.


OK, I had to go to the customer premises and found a solution. I:

  • Exported the keystore that holds the signing keys in PKCS #12 format
  • Opened control panel Java -> Security tab
  • Clicked Manage certificates
  • Imported this new keystore as a secure site CA

Then I opened the JAWS application without any warning. This is a little bit cumbersome, but much cheaper than buying a signed certificate!

How to globally replace a forward slash in a JavaScript string?

You need to wrap the forward slash to avoid cross browser issues or //commenting out.

str = 'this/that and/if';

var newstr = str.replace(/[/]/g, 'ForwardSlash');

Go back button in a page

There's a few ways, this is one:

window.history.go(-1);

C++ convert string to hexadecimal and vice versa

This is a bit faster:

static const char* s_hexTable[256] = 
{
    "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11",
    "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23",
    "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34", "35",
    "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47",
    "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59",
    "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b",
    "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d",
    "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f",
    "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0", "a1",
    "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3",
    "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5",
    "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7",
    "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9",
    "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb",
    "fc", "fd", "fe", "ff"
};

// Convert binary data sequence [beginIt, endIt) to hexadecimal string
void dataToHexString(const uint8_t*const beginIt, const uint8_t*const endIt, string& str)
{
    str.clear();
    str.reserve((endIt - beginIt) * 2);
    for(const uint8_t* it(beginIt); it != endIt; ++it)
    {
        str += s_hexTable[*it];
    }
}

How to fix apt-get: command not found on AWS EC2?

please, be sure your connected to a ubuntu server, I Had the same problem but I was connected to other distro, check the AMI value in your details instance, it should be something like

AMI: ubuntu/images/ebs/ubuntu-precise-12.04-amd64-server-20130411.1 

hope it helps

Problems with local variable scope. How to solve it?

You have a scope problem indeed, because statement is a local method variable defined here:

protected void createContents() {
    ...
    Statement statement = null; // local variable
    ...
     btnInsert.addMouseListener(new MouseAdapter() { // anonymous inner class
        @Override
        public void mouseDown(MouseEvent e) {
            ...
            try {
                statement.executeUpdate(query); // local variable out of scope here
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            ...
    });
}

When you try to access this variable inside mouseDown() method you are trying to access a local variable from within an anonymous inner class and the scope is not enough. So it definitely must be final (which given your code is not possible) or declared as a class member so the inner class can access this statement variable.

Sources:


How to solve it?

You could...

Make statement a class member instead of a local variable:

public class A1 { // Note Java Code Convention, also class name should be meaningful   
    private Statement statement;
    ...
}

You could...

Define another final variable and use this one instead, as suggested by @HotLicks:

protected void createContents() {
    ...
    Statement statement = null;
    try {
        statement = connect.createStatement();
        final Statement innerStatement = statement;
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ...
}

But you should...

Reconsider your approach. If statement variable won't be used until btnInsert button is pressed then it doesn't make sense to create a connection before this actually happens. You could use all local variables like this:

btnInsert.addMouseListener(new MouseAdapter() {
   @Override
   public void mouseDown(MouseEvent e) {
       try {
           Class.forName("com.mysql.jdbc.Driver");
           try (Connection connect = DriverManager.getConnection(...);
                Statement statement = connect.createStatement()) {

                // execute the statement here

           } catch (SQLException ex) {
               ex.printStackTrace();
           }

       } catch (ClassNotFoundException ex) {
           e.printStackTrace();
       }
});

Get Memory Usage in Android

I use this function to calculate cpu usage. Hope it can help you.

private float readUsage() {
    try {
        RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
        String load = reader.readLine();

        String[] toks = load.split(" +");  // Split on one or more spaces

        long idle1 = Long.parseLong(toks[4]);
        long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[5])
              + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

        try {
            Thread.sleep(360);
        } catch (Exception e) {}

        reader.seek(0);
        load = reader.readLine();
        reader.close();

        toks = load.split(" +");

        long idle2 = Long.parseLong(toks[4]);
        long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[5])
            + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

        return (float)(cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1));

    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return 0;
} 

De-obfuscate Javascript code to make it readable again

Try this: http://jsbeautifier.org/

I tested with your code and worked as good as possible. =D

Display PNG image as response to jQuery AJAX request

Method 1

You should not make an ajax call, just put the src of the img element as the url of the image.

This would be useful if you use GET instead of POST

<script type="text/javascript" > 

  $(document).ready( function() { 
      $('.div_imagetranscrits').html('<img src="get_image_probes_via_ajax.pl?id_project=xxx" />')
  } );

</script>

Method 2

If you want to POST to that image and do it the way you do (trying to parse the contents of the image on the client side, you could try something like this: http://en.wikipedia.org/wiki/Data_URI_scheme

You'll need to encode the data to base64, then you could put data:[<MIME-type>][;charset=<encoding>][;base64],<data> into the img src

as example:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot img" />

To encode to base64:

How to scroll to top of a div using jQuery?

Use the following function

window.scrollTo(xpos, ypos)

Here xpos is Required. The coordinate to scroll to, along the x-axis (horizontal), in pixels

ypos is also Required. The coordinate to scroll to, along the y-axis (vertical), in pixels

Two Page Login with Spring Security 3.2.x

There should be three pages here:

  1. Initial login page with a form that asks for your username, but not your password.
  2. You didn't mention this one, but I'd check whether the client computer is recognized, and if not, then challenge the user with either a CAPTCHA or else a security question. Otherwise the phishing site can simply use the tendered username to query the real site for the security image, which defeats the purpose of having a security image. (A security question is probably better here since with a CAPTCHA the attacker could have humans sitting there answering the CAPTCHAs to get at the security images. Depends how paranoid you want to be.)
  3. A page after that that displays the security image and asks for the password.

I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.

I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.

You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST submission on step 1 (and 2 if applicable).

Set textbox to readonly and background color to grey in jquery

Can add disable like below and can get data on submit. something like this .. DEMO

Html

<input type="hidden" name="email" value="email" />
<input type="text" id="dis" class="disable" value="email"   name="email" >

JS

 $("#dis").attr('disabled','disabled');

CSS

    .disable { opacity : .35; background-color:lightgray; border:1px solid gray;}

Why am I getting string does not name a type Error?

Your using declaration is in game.cpp, not game.h where you actually declare string variables. You intended to put using namespace std; into the header, above the lines that use string, which would let those lines find the string type defined in the std namespace.

As others have pointed out, this is not good practice in headers -- everyone who includes that header will also involuntarily hit the using line and import std into their namespace; the right solution is to change those lines to use std::string instead

Make an image width 100% of parent div, but not bigger than its own width

I found an answer which worked for me and can be found in the following link:

Full Width Containers in Limited Width Parents

PHP case-insensitive in_array function

I wrote a simple function to check for a insensitive value in an array the code is below.

function:

function in_array_insensitive($needle, $haystack) {
   $needle = strtolower($needle);
   foreach($haystack as $k => $v) {
      $haystack[$k] = strtolower($v);
   }
   return in_array($needle, $haystack);
}

how to use:

$array = array('one', 'two', 'three', 'four');
var_dump(in_array_insensitive('fOUr', $array));

Using the && operator in an if statement

So to make your expression work, changing && for -a will do the trick.

It is correct like this:

 if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
 then  ....

or like

 if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
 then  ....

or even

 if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
 then  ....

You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.

Convert JS object to JSON string

The existing JSON replacements where too much for me, so I wrote my own function. This seems to work, but I might have missed several edge cases (that don't occur in my project). And will probably not work for any pre-existing objects, only for self-made data.

function simpleJSONstringify(obj) {
    var prop, str, val,
        isArray = obj instanceof Array;

    if (typeof obj !== "object") return false;

    str = isArray ? "[" : "{";

    function quote(str) {
        if (typeof str !== "string") str = str.toString();
        return str.match(/^\".*\"$/) ? str : '"' + str.replace(/"/g, '\\"') + '"'
    }

    for (prop in obj) {
        if (!isArray) {
            // quote property
            str += quote(prop) + ": ";
        }

        // quote value
        val = obj[prop];
        str += typeof val === "object" ? simpleJSONstringify(val) : quote(val);
        str += ", ";
    }

    // Remove last colon, close bracket
    str = str.substr(0, str.length - 2)  + ( isArray ? "]" : "}" );

    return str;
}

How to differ sessions in browser-tabs?

Note: The solution here needs to be done at application design stage. It would be difficult to engineer this in later.

Use a hidden field to pass around the session identifier.

For this to work each page must include a form:

<form method="post" action="/handler">

  <input type="hidden" name="sessionId" value="123456890123456890ABCDEF01" />
  <input type="hidden" name="action" value="" />

</form>

Every action on your side, including navigation, POSTs the form back (setting the action as appropriate). For "unsafe" requests, you could include another parameter, say containing a JSON value of the data to be submitted:

<input type="hidden" name="action" value="completeCheckout" />
<input type="hidden" name="data" value='{ "cardNumber" : "4111111111111111", ... ' />

As there are no cookies, each tab will be independent and will have no knowledge of other sessions in the same browser.

Lots of advantages, particularly when it comes to security:

  • No reliance on JavaScript or HTML5.
  • Inherently protects against CSRF.
  • No reliance on cookies, so protects against POODLE.
  • Not vulnerable to session fixation.
  • Can prevent back button use, which is desirable when you want users to follow a set path through your site (which means logic bugs that can sometimes be attacked by out-of-order requests, can be prevented).

Some disadvantages:

  • Back button functionality may be desired.
  • Not very effective with caching as every action is a POST.

Further information here.

MongoDB: Combine data from multiple collections into one..how?

Starting Mongo 4.4, we can achieve this join within an aggregation pipeline by coupling the new $unionWith aggregation stage with $group's new $accumulator operator:

// > db.users.find()
//   [{ user: 1, name: "x" }, { user: 2, name: "y" }]
// > db.books.find()
//   [{ user: 1, book: "a" }, { user: 1, book: "b" }, { user: 2, book: "c" }]
// > db.movies.find()
//   [{ user: 1, movie: "g" }, { user: 2, movie: "h" }, { user: 2, movie: "i" }]
db.users.aggregate([
  { $unionWith: "books"  },
  { $unionWith: "movies" },
  { $group: {
    _id: "$user",
    user: {
      $accumulator: {
        accumulateArgs: ["$name", "$book", "$movie"],
        init: function() { return { books: [], movies: [] } },
        accumulate: function(user, name, book, movie) {
          if (name) user.name = name;
          if (book) user.books.push(book);
          if (movie) user.movies.push(movie);
          return user;
        },
        merge: function(userV1, userV2) {
          if (userV2.name) userV1.name = userV2.name;
          userV1.books.concat(userV2.books);
          userV1.movies.concat(userV2.movies);
          return userV1;
        },
        lang: "js"
      }
    }
  }}
])
// { _id: 1, user: { books: ["a", "b"], movies: ["g"], name: "x" } }
// { _id: 2, user: { books: ["c"], movies: ["h", "i"], name: "y" } }
  • $unionWith combines records from the given collection within documents already in the aggregation pipeline. After the 2 union stages, we thus have all users, books and movies records within the pipeline.

  • We then $group records by $user and accumulate items using the $accumulator operator allowing custom accumulations of documents as they get grouped:

    • the fields we're interested in accumulating are defined with accumulateArgs.
    • init defines the state that will be accumulated as we group elements.
    • the accumulate function allows performing a custom action with a record being grouped in order to build the accumulated state. For instance, if the item being grouped has the book field defined, then we update the books part of the state.
    • merge is used to merge two internal states. It's only used for aggregations running on sharded clusters or when the operation exceeds memory limits.

Css height in percent not working

This is what you need in the CSS:

html, body {
    height: 100%; 
    width: 100%; 
    margin: 0; 
}

How do I load an HTTP URL with App Transport Security enabled in iOS 9?

Compiling answers given by @adurdin and @User

Add followings to your info.plist & change localhost.com with your corresponding domain name, you can add multiple domains as well:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSExceptionDomains</key>
    <dict>
        <key>localhost.com</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <false/>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <false/>
            <key>NSExceptionRequiresForwardSecrecy</key>
            <true/>
            <key>NSExceptionMinimumTLSVersion</key>
            <string>TLSv1.2</string>
            <key>NSThirdPartyExceptionAllowsInsecureHTTPLoads</key>
            <false/>
            <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
            <true/>
            <key>NSThirdPartyExceptionMinimumTLSVersion</key>
            <string>TLSv1.2</string>
            <key>NSRequiresCertificateTransparency</key>
            <false/>
        </dict>
    </dict>
</dict>
</plist>

You info.plist must looks like this:

enter image description here

How to cast Object to boolean?

If the object is actually a Boolean instance, then just cast it:

boolean di = (Boolean) someObject;

The explicit cast will do the conversion to Boolean, and then there's the auto-unboxing to the primitive value. Or you can do that explicitly:

boolean di = ((Boolean) someObject).booleanValue();

If someObject doesn't refer to a Boolean value though, what do you want the code to do?

How to customize the background color of a UITableViewCell?

Customizing the background of a table view cell eventually becomes and "all or nothing" approach. It's very difficult to change the color or image used for the background of a content cell in a way that doesn't look strange.

The reason is that the cell actually spans the width of the view. The rounded corners are just part of its drawing style and the content view sits in this area.

If you change the color of the content cell you will end up with white bits visible at the corners. If you change the color of the entire cell, you will have a block of color spanning the width of the view.

You can definitely customize a cell, but it's not quite as easy as you may think at first.

Python string prints as [u'String']

encode("latin-1") helped me in my case:

facultyname[0].encode("latin-1")

If else on WHERE clause

Here is a sample query for a table having a foreign key relationship to the same table with a query parameter.

enter image description here

SET @x = -1;
SELECT id, categoryName 
FROM Catergory WHERE IF(@x > 0,category_ParentId = @x,category_ParentId IS NOT NULL);

@x can be changed.

Progress Bar with HTML and CSS

If you wish to have a progress bar without adding some code PACE can be an awesome tool for you.

Just include pace.js and a CSS theme of your choice, and you get a beautiful progress indicator for your page load and AJAX navigation. Best thing with PACE is the auto detection of progress.

It contains various themes and color schemes as well.

Worth a try.

Catching access violation exceptions?

A violation like that means that there's something seriously wrong with the code, and it's unreliable. I can see that a program might want to try to save the user's data in a way that one hopes won't write over previous data, in the hope that the user's data isn't already corrupted, but there is by definition no standard method of dealing with undefined behavior.

Using find to locate files that match one of multiple patterns

Use -o, which means "or":

find Documents \( -name "*.py" -o -name "*.html" \)

You'd need to build that command line programmatically, which isn't that easy.

Are you using bash (or Cygwin on Windows)? If you are, you should be able to do this:

ls **/*.py **/*.html

which might be easier to build programmatically.

jQuery to loop through elements with the same class

try this...

$('.testimonial').each(function(){
    //if statement here 
    // use $(this) to reference the current div in the loop
    //you can try something like...


    if(condition){

    }


 });

How to get only numeric column values?

SELECT column1 FROM table WHERE column1 not like '%[0-9]%'

Removing the '^' did it for me. I'm looking at a varchar field and when I included the ^ it excluded all of my non-numerics which is exactly what I didn't want. So, by removing ^ I only got non-numeric values back.

Netbeans - class does not have a main method

Sometimes passing parameters in the main method causes this problem eg. public static void main(String[] args,int a). If you declare the variable outside the main method, it might help :)

Postgresql : syntax error at or near "-"

i was trying trying to GRANT read-only privileges to a particular table to a user called walters-ro. So when i ran the sql command # GRANT SELECT ON table_name TO walters-ro; --- i got the following error..`syntax error at or near “-”

The solution to this was basically putting the user_name into double quotes since there is a dash(-) between the name.

# GRANT SELECT ON table_name TO "walters-ro";

That solved the problem.

href="file://" doesn't work

The reason your URL is being rewritten to file///K:/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf is because you specified http://file://

The http:// at the beginning is the protocol being used, and your browser is stripping out the second colon (:) because it is invalid.

Note

If you link to something like

<a href="file:///K:/yourfile.pdf">yourfile.pdf</a>

The above represents a link to a file called k:/yourfile.pdf on the k: drive on the machine on which you are viewing the URL.

You can do this, for example the below creates a link to C:\temp\test.pdf

<a href="file:///C:/Temp/test.pdf">test.pdf</a>

By specifying file:// you are indicating that this is a local resource. This resource is NOT on the internet.

Most people do not have a K:/ drive.

But, if this is what you are trying to achieve, that's fine, but this is not how a "typical" link on a web page works, and you shouldn't being doing this unless everyone who is going to access your link has access to the (same?) K:/drive (this might be the case with a shared network drive).

You could try

<a href="file:///K:/AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>
<a href="AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>
<a href="2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>

Note that http://file:///K:/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf is a malformed

How to escape indicator characters (i.e. : or - ) in YAML

Quotes, but I prefer them on the just the value:

url: "http://www.example.com/"

Putting them across the whole line looks like it might cause problems.

Why would Oracle.ManagedDataAccess not work when Oracle.DataAccess does?

Once I found what format it was looking for in the connection string, it worked just fine like this with Oracle.ManagedDataAccess. Without having to mess around with anything separately.

DATA SOURCE=DSDSDS:1521/ORCL;

PHP Fatal error: Class 'PDO' not found

If you have upgraded your PHP version, make sure that the old PHP version configuration in your .htaccess has been deleted. For more info, check this https://www.hostgator.com/help/article/php-configuration-plugin

Setting HttpContext.Current.Session in a unit test

Try this:

        // MockHttpSession Setup
        var session = new MockHttpSession();

        // MockHttpRequest Setup - mock AJAX request
        var httpRequest = new Mock<HttpRequestBase>();

        // Setup this part of the HTTP request for AJAX calls
        httpRequest.Setup(req => req["X-Requested-With"]).Returns("XMLHttpRequest");

        // MockHttpContextBase Setup - mock request, cache, and session
        var httpContext = new Mock<HttpContextBase>();
        httpContext.Setup(ctx => ctx.Request).Returns(httpRequest.Object);
        httpContext.Setup(ctx => ctx.Cache).Returns(HttpRuntime.Cache);
        httpContext.Setup(ctx => ctx.Session).Returns(session);

        // MockHttpContext for cache
        var contextRequest = new HttpRequest("", "http://localhost/", "");
        var contextResponse = new HttpResponse(new StringWriter());
        HttpContext.Current = new HttpContext(contextRequest, contextResponse);

        // MockControllerContext Setup
        var context = new Mock<ControllerContext>();
        context.Setup(ctx => ctx.HttpContext).Returns(httpContext.Object);

        //TODO: Create new controller here
        //      Set controller's ControllerContext to context.Object

And Add the class:

public class MockHttpSession : HttpSessionStateBase
{
    Dictionary<string, object> _sessionDictionary = new Dictionary<string, object>();
    public override object this[string name]
    {
        get
        {
            return _sessionDictionary.ContainsKey(name) ? _sessionDictionary[name] : null;
        }
        set
        {
            _sessionDictionary[name] = value;
        }
    }

    public override void Abandon()
    {
        var keys = new List<string>();

        foreach (var kvp in _sessionDictionary)
        {
            keys.Add(kvp.Key);
        }

        foreach (var key in keys)
        {
            _sessionDictionary.Remove(key);
        }
    }

    public override void Clear()
    {
        var keys = new List<string>();

        foreach (var kvp in _sessionDictionary)
        {
            keys.Add(kvp.Key);
        }

        foreach(var key in keys)
        {
            _sessionDictionary.Remove(key);
        }
    }
}

This will allow you to test with both session and cache.

Downloading jQuery UI CSS from Google's CDN

jQuery now has a CDN access:

code.jquery.com/ui/[version]/themes/[theme name]/jquery-ui.css


And to make this a little more easy, Here you go:

How to forcefully set IE's Compatibility Mode off from the server-side?

Update: More useful information What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

Maybe this url can help you: Activating Browser Modes with Doctype

Edit: Today we were able to override the compatibility view with: <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />

Toggle show/hide on click with jQuery

$(document).ready( function(){
  $("button").click(function(){
    $("p").toggle(1000,'linear');
  });
});

Live Demo

Allow anything through CORS Policy

Use VSC or any other editor that has Live server, it will give you a proxy that will allow you to use GET or FETCH

Cannot get OpenCV to compile because of undefined references?

I have tried all solution. The -lopencv_core -lopencv_imgproc -lopencv_highgui in comments solved my problem. And know my command line looks like this in geany:

g++ -lopencv_core -lopencv_imgproc -lopencv_highgui  -o "%e" "%f"

When I build:

g++ -lopencv_core -lopencv_imgproc -lopencv_highgui  -o "opencv" "opencv.cpp" (in directory: /home/fedora/Desktop/Implementations)

The headers are:

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

Validation of radio button group using jQuery validation plugin

Another way to validate is like this.

var $radio = $('input:radio[name="nameRadioButton"]');
$radio.addClass("validate[required]");

I hope my example will help you

Rails has_many with alias name

Give this a shot:

has_many :jobs, foreign_key: "user_id", class_name: "Task"

Note, that :as is used for polymorphic associations.

Calling a parent window function from an iframe

While some of these solutions may work, none of them follow best practices. Many assign global variables and you may find yourself making calls to multiple parent variables or functions, leading to a cluttered, vulnerable namespace.

To avoid this, use a module pattern. In the parent window:

var myThing = {
    var i = 0;
    myFunction : function () {
        // do something
    }
};

var newThing = Object.create(myThing);

Then, in the iframe:

function myIframeFunction () {
    parent.myThing.myFunction();
    alert(parent.myThing.i);
};

This is similar to patterns described in the Inheritance chapter of Crockford's seminal text, "Javascript: The Good Parts." You can also learn more at w3's page for Javascript's best practices. https://www.w3.org/wiki/JavaScript_best_practices#Avoid_globals

How to use java.Set

Did you override equals and hashCode in the Block class?

EDIT:

I assumed you mean it doesn't work at runtime... did you mean that or at compile time? If compile time what is the error message? If it crashes at runtime what is the stack trace? If it compiles and runs but doesn't work right then the equals and hashCode are the likely issue.

MySQL set current date in a DATETIME field on insert

DELIMITER ;;
CREATE TRIGGER `my_table_bi` BEFORE INSERT ON `my_table` FOR EACH ROW
BEGIN
    SET NEW.created_date = NOW();
END;;
DELIMITER ;

How to get the path of src/test/resources directory in JUnit?

Use the following to inject Hibernate with Spring in your unit tests:

@Bean
public LocalSessionFactoryBean getLocalSessionFactoryBean() {
    LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
    localSessionFactoryBean.setConfigLocation(new ClassPathResource("hibernate.cfg.xml"));
    localSessionFactoryBean.setPackagesToScan("com.example.yourpackage.model");
    return localSessionFactoryBean;
}

If you don't have the hibernate.cfg.xml present in your src/test/resources folder it will automatically fall back to the one in your src/main/resources folder.

SQL: how to select a single id ("row") that meets multiple criteria from a single column

This question is some years old but i came via a duplicate to it. I want to suggest a more general solution too. If you know you always have a fixed number of ancestors you can use some self joins as already suggested in the answers. If you want a generic approach go on reading.

What you need here is called Quotient in relational Algebra. The Quotient is more or less the reversal of the Cartesian Product (or Cross Join in SQL).

Let's say your ancestor set A is (i use a table notation here, i think this is better for understanding)

ancestry
-----------
'England'
'France'
'Germany'

and your user set U is

user_id
--------
   1
   2
   3

The cartesian product C=AxU is then:

user_id  |  ancestry
---------+-----------
   1     | 'England'
   1     | 'France'
   1     | 'Germany'
   2     | 'England'
   2     | 'France'
   2     | 'Germany'
   3     | 'England'
   3     | 'France'
   3     | 'Germany'

If you calculate the set quotient U=C/A then you get

user_id
--------
   1
   2
   3

If you redo the cartesian product UXA you will get C again. But note that for a set T, (T/A)xA will not necessarily reproduce T. For example, if T is

user_id  |  ancestry
---------+-----------
   1     | 'England'
   1     | 'France'
   1     | 'Germany'
   2     | 'England'
   2     | 'France'

then (T/A) is

user_id
--------
   1

(T/A)xA will then be

user_id  |  ancestry
---------+------------
   1     | 'England'
   1     | 'France'
   1     | 'Germany'

Note that the records for user_id=2 have been eliminated by the Quotient and Cartesian Product operations.

Your question is: Which user_id has ancestors from all countries in your ancestor set? In other words you want U=T/A where T is your original set (or your table).

To implement the quotient in SQL you have to do 4 steps:

  1. Create the Cartesian Product of your ancestry set and the set of all user_ids.
  2. Find all records in the Cartesian Product which have no partner in the original set (Left Join)
  3. Extract the user_ids from the resultset of 2)
  4. Return all user_ids from the original set which are not included in the result set of 3)

So let's do it step by step. I will use TSQL syntax (Microsoft SQL server) but it should easily be adaptable to other DBMS. As a name for the table (user_id, ancestry) i choose ancestor

CREATE TABLE ancestry_set (ancestry nvarchar(25))
INSERT INTO ancestry_set (ancestry) VALUES ('England')
INSERT INTO ancestry_set (ancestry) VALUES ('France')
INSERT INTO ancestry_set (ancestry) VALUES ('Germany')

CREATE TABLE ancestor ([user_id] int, ancestry nvarchar(25))
INSERT INTO ancestor ([user_id],ancestry) VALUES (1,'England')
INSERT INTO ancestor ([user_id],ancestry) VALUES(1,'Ireland')
INSERT INTO ancestor ([user_id],ancestry) VALUES(2,'France')
INSERT INTO ancestor ([user_id],ancestry) VALUES(3,'Germany')
INSERT INTO ancestor ([user_id],ancestry) VALUES(3,'Poland')
INSERT INTO ancestor ([user_id],ancestry) VALUES(4,'England')
INSERT INTO ancestor ([user_id],ancestry) VALUES(4,'France')
INSERT INTO ancestor ([user_id],ancestry) VALUES(4,'Germany')
INSERT INTO ancestor ([user_id],ancestry) VALUES(5,'France')
INSERT INTO ancestor ([user_id],ancestry) VALUES(5,'Germany')

1) Create the Cartesian Product of your ancestry set and the set of all user_ids.

SELECT a.[user_id],s.ancestry
FROM ancestor a, ancestry_set s
GROUP BY a.[user_id],s.ancestry

2) Find all records in the Cartesian Product which have no partner in the original set (Left Join) and

3) Extract the user_ids from the resultset of 2)

SELECT DISTINCT cp.[user_id]
FROM (SELECT a.[user_id],s.ancestry
      FROM ancestor a, ancestry_set s
      GROUP BY a.[user_id],s.ancestry) cp
   LEFT JOIN ancestor a ON cp.[user_id]=a.[user_id] AND cp.ancestry=a.ancestry
WHERE a.[user_id] is null

4) Return all user_ids from the original set which are not included in the result set of 3)

SELECT DISTINCT [user_id]
FROM ancestor
WHERE [user_id] NOT IN (
   SELECT DISTINCT cp.[user_id]
   FROM (SELECT a.[user_id],s.ancestry
         FROM ancestor a, ancestry_set s
         GROUP BY a.[user_id],s.ancestry) cp
   LEFT JOIN ancestor a ON cp.[user_id]=a.[user_id] AND cp.ancestry=a.ancestry
   WHERE a.[user_id] is null
   )

Regular Expression to match string starting with a specific word

If you want to match anything after a word stop an not only at the start of the line you may use : \bstop.*\b - word followed by line

Word till the end of string

Or if you want to match the word in the string use \bstop[a-zA-Z]* - only the words starting with stop

Only the words starting with stop

Or the start of lines with stop ^stop[a-zA-Z]* for the word only - first word only
The whole line ^stop.* - first line of the string only

And if you want to match every string starting with stop including newlines use : /^stop.*/s - multiline string starting with stop

How to add text to JFrame?

The easiest way to add a text to a JFrame:

JFrame window = new JFrame("JFrame with text"); 
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(new BorderLayout());
window.add(new JLabel("Hello World"), BorderLayout.CENTER);
window.pack();
window.setVisible(true);
window.setLocationRelativeTo(null);

Changing the git user inside Visual Studio Code

Press Ctrl + Shift + G in Visual Studio Code and go to more and select Show git output. Click Terminal and type git remote -v and verify that the origin branch has latest username in it like:

origin [email protected]:DroidPulkit/Facebook-Chat-Bot.git (fetch)

origin [email protected]:DroidPulkit/Facebook-Chat-Bot.git (push)

Here DroidPulkit is my username.

If the username is not what you wanted it to be then change it with:

git add remote origin [email protected]:newUserName/RepoName.git

useState set method not reflecting change immediately

Much like setState in Class components created by extending React.Component or React.PureComponent, the state update using the updater provided by useState hook is also asynchronous, and will not be reflected immediately.

Also, the main issue here is not just the asynchronous nature but the fact that state values are used by functions based on their current closures, and state updates will reflect in the next re-render by which the existing closures are not affected, but new ones are created. Now in the current state, the values within hooks are obtained by existing closures, and when a re-render happens, the closures are updated based on whether the function is recreated again or not.

Even if you add a setTimeout the function, though the timeout will run after some time by which the re-render would have happened, the setTimeout will still use the value from its previous closure and not the updated one.

setMovies(result);
console.log(movies) // movies here will not be updated

If you want to perform an action on state update, you need to use the useEffect hook, much like using componentDidUpdate in class components since the setter returned by useState doesn't have a callback pattern

useEffect(() => {
    // action on update of movies
}, [movies]);

As far as the syntax to update state is concerned, setMovies(result) will replace the previous movies value in the state with those available from the async request.

However, if you want to merge the response with the previously existing values, you must use the callback syntax of state updation along with the correct use of spread syntax like

setMovies(prevMovies => ([...prevMovies, ...result]));

Can I write or modify data on an RFID tag?

Some RFID chips are read-write, the majority are read-only. You can find out if your chip is read-only by checking the datasheet.

How can I use JSON data to populate the options of a select box?

zeusstl is right. it works for me too.

   <select class="form-control select2" id="myselect">
                      <option disabled="disabled" selected></option>
                      <option>Male</option>
                      <option>Female</option>
                    </select>

   $.getJSON("mysite/json1.php", function(json){
        $('#myselect').empty();
        $('#myselect').append($('<option>').text("Select"));
        $.each(json, function(i, obj){

  $('#myselect').append($('<option>').text(obj.text).attr('value', obj.val));
        });
  });

In Eclipse, what can cause Package Explorer "red-x" error-icon when all Java sources compile without errors?

This happened when i downloaded fabric.io on Eclipse Mars but Restarting computer solved this problem for me.

How do you turn a Mongoose document into a plain object?

the fast way if the property is not in the model :

document.set( key,value, { strict: false });

Convert a string to an enum in C#

Note that the performance of Enum.Parse() is awful, because it is implemented via reflection. (The same is true of Enum.ToString, which goes the other way.)

If you need to convert strings to Enums in performance-sensitive code, your best bet is to create a Dictionary<String,YourEnum> at startup and use that to do your conversions.

How to set username and password for SmtpClient object in .NET?

The SmtpClient can be used by code:

SmtpClient mailer = new SmtpClient();
mailer.Host = "mail.youroutgoingsmtpserver.com";
mailer.Credentials = new System.Net.NetworkCredential("yourusername", "yourpassword");

Set folder browser dialog start location

In my case, it was an accidental double escaping.

this works:

SelectedPath = @"C:\Program Files\My Company\My product";

this doesn't:

SelectedPath = @"C:\\Program Files\\My Company\\My product";

Apache POI Excel - how to configure columns to be expanded?

You can use setColumnWidth() if you want to expand your cell more.

What database does Google use?

It's something they've built themselves - it's called Bigtable.

http://en.wikipedia.org/wiki/BigTable

There is a paper by Google on the database:

http://research.google.com/archive/bigtable.html

How to make an inline-block element fill the remainder of the line?

When you give up the inline blocks

.post-container {
    border: 5px solid #333;
    overflow:auto;
}
.post-thumb {
    float: left;
    display:block;
    background:#ccc;
    width:200px;
    height:200px;
}
.post-content{
    display:block;
    overflow:hidden;
}

http://jsfiddle.net/RXrvZ/3731/

(from CSS Float: Floating an image to the left of the text)