Programs & Examples On #Mapguide

MapGuide Open Source is a web-based platform that enables users to develop and deploy web mapping applications and geospatial web services.

How to clear https proxy setting of NPM?

Nothing above worked for me. I had to edit the file ".npmrc" which will be under user home directory (ex: c:\users\abcuser) :

http_proxy=null
registry=https://registry.npmjs.org/
strict-ssl=true
proxy=null

How to find the day, month and year with moment.js

If you are looking for answer in string values , try this

var check = moment('date/utc format');
day = check.format('dddd') // => ('Monday' , 'Tuesday' ----)
month = check.format('MMMM') // => ('January','February.....)
year = check.format('YYYY') // => ('2012','2013' ...)  

What's the best free C++ profiler for Windows?

There is an instrumenting (function-accurate) profiler for MS VC 7.1 and higher called MicroProfiler. You can get it here (x64) or here (x86). It doesn't require any modifications or additions to your code and is able of displaying function statistics with callers and callees in real-time without the need of closing application/stopping the profiling process.

It integrates with VisualStudio, so you can easily enable/disable profiling for a project. It is also possible to install it on the clean machine, it only needs the symbol information be located along with the executable being profiled.

This tool is useful when statistical approximation from sampling profilers like Very Sleepy isn't sufficient.

Rough comparison shows, that it beats AQTime (when it is invoked in instrumenting, function-level run). The following program (full optimization, inlining disabled) runs three times faster with micro-profiler displaying results in real-time, than with AQTime simply collecting stats:

void f()
{
    srand(time(0));

    vector<double> v(300000);

    generate_n(v.begin(), v.size(), &random);
    sort(v.begin(), v.end());
    sort(v.rbegin(), v.rend());
    sort(v.begin(), v.end());
    sort(v.rbegin(), v.rend());
}

jQuery UI autocomplete with item and id

My code only worked when I added 'return false' to the select function. Without this, the input was set with the right value inside the select function and then it was set to the id value after the select function was over. The return false solved this problem.

$('#sistema_select').autocomplete({

    minLength: 3,
    source: <?php echo $lista_sistemas;?> ,
    select: function (event, ui) {
         $('#sistema_select').val(ui.item.label); // display the selected text
         $('#sistema_select_id').val(ui.item.value); // save selected id to hidden input
         return false;
     },
    change: function( event, ui ) {
        $( "#sistema_select_id" ).val( ui.item? ui.item.value : 0 );
    } 
});

In addition, I added a function to the change event because, if the user writes something in the input or erases a part of the item label after one item was selected, I need to update the hidden field so that I don´t get the wrong (outdated) id. For example, if my source is:

var $local_source = [
       {value: 1,  label: "c++"}, 
       {value: 2,  label: "java"}]

and the user type ja and select the 'java' option with the autocomplete, I store the value 2 in the hidden field. If the user erase a letter from 'java', por exemple ending up with 'jva' in the input field, I can´t pass to my code the id 2, because the user changed the value. In this case I set the id to 0.

how can I login anonymously with ftp (/usr/bin/ftp)?

Anonymous FTP usage is covered by RFC 1635: How to Use Anonymous FTP:

What is Anonymous FTP?

Anonymous FTP is a means by which archive sites allow general access to their archives of information. These sites create a special account called "anonymous".

Traditionally, this special anonymous user account accepts any string as a password, although it is common to use either the password "guest" or one's electronic mail (e-mail) address. Some archive sites now explicitly ask for the user's e-mail address and will not allow login with the "guest" password. Providing an e-mail address is a courtesy that allows archive site operators to get some idea of who is using their services.

These are general recommendations, though. Each FTP server may have its own guidelines.

For sample use of the ftp command on anonymous FTP access, see appendix A:

atlas.arc.nasa.gov% ftp naic.nasa.gov
Connected to naic.nasa.gov.
220 naic.nasa.gov FTP server (Wed May 4 12:15:15 PDT 1994) ready.
Name (naic.nasa.gov:amarine): anonymous
331 Guest login ok, send your complete e-mail address as password.
Password:
230-----------------------------------------------------------------
230-Welcome to the NASA Network Applications and Info Center Archive
230-
230-     Access to NAIC's online services is also available through:
230-
230-        Gopher         - naic.nasa.gov (port 70)
230-    World-Wide-Web - http://naic.nasa.gov/naic/naic-home.html
230-
230-        If you experience any problems please send email to
230-
230-                    [email protected]
230-
230-                 or call +1 (800) 858-9947
230-----------------------------------------------------------------
230-
230-Please read the file README
230-  it was last modified on Fri Dec 10 13:06:33 1993 - 165 days ago
230 Guest login ok, access restrictions apply.
ftp> cd files/rfc
250-Please read the file README.rfc
250-  it was last modified on Fri Jul 30 16:47:29 1993 - 298 days ago
250 CWD command successful.
ftp> get rfc959.txt
200 PORT command successful.
150 Opening ASCII mode data connection for rfc959.txt (147316 bytes).
226 Transfer complete.
local: rfc959.txt remote: rfc959.txt
151249 bytes received in 0.9 seconds (1.6e+02 Kbytes/s)
ftp> quit
221 Goodbye.
atlas.arc.nasa.gov%

See also the example session at the University of Edinburgh site.

Run command on the Ansible host

Yes, you can run commands on the Ansible host. You can specify that all tasks in a play run on the Ansible host, or you can mark individual tasks to run on the Ansible host.

If you want to run an entire play on the Ansible host, then specify hosts: 127.0.0.1 and connection:local in the play, for example:

- name: a play that runs entirely on the ansible host
  hosts: 127.0.0.1
  connection: local
  tasks:
  - name: check out a git repository
    git: repo=git://foosball.example.org/path/to/repo.git dest=/local/path

See Local Playbooks in the Ansible documentation for more details.

If you just want to run a single task on your Ansible host, you can use local_action to specify that a task should be run locally. For example:

- name: an example playbook
  hosts: webservers
  tasks:
  - ...

  - name: check out a git repository
    local_action: git repo=git://foosball.example.org/path/to/repo.git dest=/local/path

See Delegation in the Ansible documentation for more details.

Edit: You can avoid having to type connection: local in your play by adding this to your inventory:

localhost ansible_connection=local

(Here you'd use "localhost" instead of "127.0.0.1" to refer to the play).

Edit: In newer versions of ansible, you no longer need to add the above line to your inventory, ansible assumes it's already there.

How to determine whether code is running in DEBUG / RELEASE build?

zitao xiong's answer is pretty close to what I use; I also include the file name (by stripping off the path of FILE).

#ifdef DEBUG
    #define NSLogDebug(format, ...) \
    NSLog(@"<%s:%d> %s, " format, \
    strrchr("/" __FILE__, '/') + 1, __LINE__, __PRETTY_FUNCTION__, ## __VA_ARGS__)
#else
    #define NSLogDebug(format, ...)
#endif

Getting char from string at specified index

char = split_string_to_char(text)(index)

------

Function split_string_to_char(text) As String()

   Dim chars() As String
   For char_count = 1 To Len(text)
      ReDim Preserve chars(char_count - 1)
      chars(char_count - 1) = Mid(text, char_count, 1)
   Next
   split_string_to_char = chars
End Function

Address validation using Google Maps API

I know that this post is a bit old but incase anyone finds it still relevant you might want to check out the free geocoding services offered by USC College. This does included address validation via ajax and static calls. The only catch is that they request a link back and only offer allotments of 2500 calls. More than fair. https://webgis.usc.edu/Services/AddressValidation/Default.aspx

How to get form input array into PHP array

Using this method should work:

$name = $_POST['name'];
$email = $_POST['account'];
while($explore=each($email)) {
    echo $explore['key'];
    echo "-";
    echo $explore['value'];
    echo "<br/>";
}

Add a CSS border on hover without moving the element

Try this it might solve your problem.

Css:

.item{padding-top:1px;}

.jobs .item:hover {
    background: #e1e1e1;
    border-top: 1px solid #d0d0d0;
    padding-top:0;
}

HTML:

<div class="jobs">
    <div class="item">
        content goes here
    </div>
</div>

See fiddle for output: http://jsfiddle.net/dLDNA/

Python: Binding Socket: "Address already in use"

another solution, in development environment of course, is killing process using it, for example

def serve():
    server = HTTPServer(('', PORT_NUMBER), BaseHTTPRequestHandler)
    print 'Started httpserver on port ' , PORT_NUMBER
    server.serve_forever()
try:
    serve()
except Exception, e:
    print "probably port is used. killing processes using given port %d, %s"%(PORT_NUMBER,e)
    os.system("xterm -e 'sudo fuser -kuv %d/tcp'" % PORT_NUMBER)
    serve()
    raise e

Best way to restrict a text field to numbers only?

Just use regex to get rid of any non number characters whenever a key is pressed or the textbox loses focus.

var numInput;
window.onload = function () {   
    numInput = document.getElementById('numonly');
    numInput.onkeydown = numInput.onblur = numInput.onkeyup = function()
    {
        numInput.value = numInput.value.replace(/[^0-9]+/,"");
    }
}

Multi-dimensional arrays in Bash

Bash does not support multidimensional arrays, nor hashes, and it seems that you want a hash that values are arrays. This solution is not very beautiful, a solution with an xml file should be better :

array=('d1=(v1 v2 v3)' 'd2=(v1 v2 v3)')
for elt in "${array[@]}";do eval $elt;done
echo "d1 ${#d1[@]} ${d1[@]}"
echo "d2 ${#d2[@]} ${d2[@]}"

EDIT: this answer is quite old, since since bash 4 supports hash tables, see also this answer for a solution without eval.

Check number of arguments passed to a Bash script

On []: !=, =, == ... are string comparison operators and -eq, -gt ... are arithmetic binary ones.

I would use:

if [ "$#" != "1" ]; then

Or:

if [ $# -eq 1 ]; then

How do I create a timeline chart which shows multiple events? Eg. Metallica Band members timeline on wiki

As mentioned in the earlier comment, stacked bar chart does the trick, though the data needs to be setup differently.(See image below)

Duration column = End - Start

  1. Once done, plot your stacked bar chart using the entire data.
  2. Mark start and end range to no fill.
  3. Right click on the X Axis and change Axis options manually. (This did cause me some issues, till I realized I couldn't manipulate them to enter dates, :) yeah I am newbie, excel masters! :))

enter image description here

How to create multiple output paths in Webpack config

If you can live with multiple output paths having the same level of depth and folder structure there is a way to do this in webpack 2 (have yet to test with webpack 1.x)

Basically you don't follow the doc rules and you provide a path for the filename.

module.exports = {
    entry: {
      foo: 'foo.js',
      bar: 'bar.js'
    },

    output: {
      path: path.join(__dirname, 'components'),
      filename: '[name]/dist/[name].bundle.js', // Hacky way to force webpack   to have multiple output folders vs multiple files per one path
    }
};

That will take this folder structure

/-
  foo.js
  bar.js

And turn it into

/-
  foo.js
  bar.js
  components/foo/dist/foo.js
  components/bar/dist/bar.js

Cassandra cqlsh - connection refused

It is a good idea to check the cassandra log if even the server is running. I was getting exactly the same message and unable to do anything with that and then I found out that there are errors in the log and the system is actually not working.

Silly, I know, but could happen...

How to display and hide a div with CSS?

You need

.abc,.ab {
    display: none;
}

#f:hover ~ .ab {
    display: block;
}

#s:hover ~ .abc {
    display: block;
}

#s:hover ~ .a,
#f:hover ~ .a{
    display: none;
}

Updated demo at http://jsfiddle.net/gaby/n5fzB/2/


The problem in your original CSS was that the , in css selectors starts a completely new selector. it is not combined.. so #f:hover ~ .abc,.a means #f:hover ~ .abc and .a. You set that to display:none so it was always set to be hidden for all .a elements.

Set the absolute position of a view

Try below code to set view on specific location :-

            TextView textView = new TextView(getActivity());
            textView.setId(R.id.overflowCount);
            textView.setText(count + "");
            textView.setGravity(Gravity.CENTER);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
            textView.setTextColor(getActivity().getResources().getColor(R.color.white));
            textView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // to handle click 
                }
            });
            // set background 
            textView.setBackgroundResource(R.drawable.overflow_menu_badge_bg);

            // set apear

            textView.animate()
                    .scaleXBy(.15f)
                    .scaleYBy(.15f)
                    .setDuration(700)
                    .alpha(1)
                    .setInterpolator(new BounceInterpolator()).start();
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.WRAP_CONTENT,
                    FrameLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.topMargin = 100; // margin in pixels, not dps
            layoutParams.leftMargin = 100; // margin in pixels, not dps
            textView.setLayoutParams(layoutParams);

            // add into my parent view
            mainFrameLaout.addView(textView);

Spring Boot without the web server

Spring Boot 2.x

  • Application Properties

    spring.main.web-application-type=NONE 
    # REACTIVE, SERVLET
    
  • or SpringApplicationBuilder

    @SpringBootApplication
    public class MyApplication {
    
        public static void main(String[] args) {
            new SpringApplicationBuilder(MyApplication.class)
                .web(WebApplicationType.NONE) // .REACTIVE, .SERVLET
                .run(args);
       }
    }
    

Where WebApplicationType:

  • NONE - The application should not run as a web application and should not start an embedded web server.
  • REACTIVE - The application should run as a reactive web application and should start an embedded reactive web server.
  • SERVLET - The application should run as a servlet-based web application and should start an embedded servlet web server.

Rounding numbers to 2 digits after comma

UPDATE: Keep in mind, at the time the answer was initially written in 2010, the bellow function toFixed() worked slightly different. toFixed() seems to do some rounding now, but not in the strictly mathematical manner. So be careful with it. Do your tests... The method described bellow will do rounding well, as mathematician would expect.

  • toFixed() - method converts a number into a string, keeping a specified number of decimals. It does not actually rounds up a number, it truncates the number.
  • Math.round(n) - rounds a number to the nearest integer. Thus turning:

0.5 -> 1; 0.05 -> 0

so if you want to round, say number 0.55555, only to the second decimal place; you can do the following(this is step-by-step concept):

  • 0.55555 * 100 = 55.555
  • Math.Round(55.555) -> 56.000
  • 56.000 / 100 = 0.56000
  • (0.56000).toFixed(2) -> 0.56

and this is the code:

(Math.round(number * 100)/100).toFixed(2);

How to hash a password

I use a hash and a salt for my password encryption (it's the same hash that Asp.Net Membership uses):

private string PasswordSalt
{
   get
   {
      var rng = new RNGCryptoServiceProvider();
      var buff = new byte[32];
      rng.GetBytes(buff);
      return Convert.ToBase64String(buff);
   }
}

private string EncodePassword(string password, string salt)
{
   byte[] bytes = Encoding.Unicode.GetBytes(password);
   byte[] src = Encoding.Unicode.GetBytes(salt);
   byte[] dst = new byte[src.Length + bytes.Length];
   Buffer.BlockCopy(src, 0, dst, 0, src.Length);
   Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
   HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
   byte[] inarray = algorithm.ComputeHash(dst);
   return Convert.ToBase64String(inarray);
}

DropDownList in MVC 4 with Razor

@{var listItems = new List<ListItem>
    {
          new ListItem { Text = "Exemplo1", Value="Exemplo1" },
          new ListItem { Text = "Exemplo2", Value="Exemplo2" },
          new ListItem { Text = "Exemplo3", Value="Exemplo3" }
    };
    }
        @Html.DropDownList("Exemplo",new SelectList(listItems,"Value","Text"))

IntelliJ - show where errors are

In my case, IntelliJ was simply in power safe mode

Excel VBA - select multiple columns not in sequential order

Some of the code looks a bit complex to me. This is very simple code to select only the used rows in two discontiguous columns D and H. It presumes the columns are of unequal length and thus more flexible vs if the columns were of equal length.

As you most likely surmised 4=column D and 8=column H

Dim dlastRow As Long
Dim hlastRow As Long

dlastRow = ActiveSheet.Cells(Rows.Count, 4).End(xlUp).Row
hlastRow = ActiveSheet.Cells(Rows.Count, 8).End(xlUp).Row
Range("D2:D" & dlastRow & ",H2:H" & hlastRow).Select

Hope you find useful - DON'T FORGET THAT COMMA BEFORE THE SECOND COLUMN, AS I DID, OR IT WILL BOMB!!

read file from assets

If you use other any class other than Activity, you might want to do like,

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader( YourApplication.getInstance().getAssets().open("text.txt"), "UTF-8"));

Using python PIL to turn a RGB image into a pure black and white image

from PIL import Image 
image_file = Image.open("convert_image.png") # open colour image
image_file = image_file.convert('1') # convert image to black and white
image_file.save('result.png')

yields

enter image description here

Bad Gateway 502 error with Apache mod_proxy and Tomcat

you should be able to get this problem resolved through a timeout and proxyTimeout parameter set to 600 seconds. It worked for me after battling for a while.

How to access first element of JSON object array?

'[{"event":"inbound","ts":1426249238}]' is a string, you cannot access any properties there. You will have to parse it to an object, with JSON.parse() and then handle it like a normal object

How to programmatically close a JFrame

This examples shows how to realize the confirmed window close operation.

The window has a Window adapter which switches the default close operation to EXIT_ON_CLOSEor DO_NOTHING_ON_CLOSE dependent on your answer in the OptionDialog.

The method closeWindow of the ConfirmedCloseWindow fires a close window event and can be used anywhere i.e. as an action of an menu item

public class WindowConfirmedCloseAdapter extends WindowAdapter {

    public void windowClosing(WindowEvent e) {

        Object options[] = {"Yes", "No"};

        int close = JOptionPane.showOptionDialog(e.getComponent(),
                "Really want to close this application?\n", "Attention",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.INFORMATION_MESSAGE,
                null,
                options,
                null);

        if(close == JOptionPane.YES_OPTION) {
           ((JFrame)e.getSource()).setDefaultCloseOperation(
                   JFrame.EXIT_ON_CLOSE);
        } else {
           ((JFrame)e.getSource()).setDefaultCloseOperation(
                   JFrame.DO_NOTHING_ON_CLOSE);
        }
    }
}

public class ConfirmedCloseWindow extends JFrame {

    public ConfirmedCloseWindow() {

        addWindowListener(new WindowConfirmedCloseAdapter());
    }

    private void closeWindow() {
        processWindowEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
    }
}

Validating an XML against referenced XSD in C#

The following example validates an XML file and generates the appropriate error or warning.

using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;

public class Sample
{

    public static void Main()
    {
        //Load the XmlSchemaSet.
        XmlSchemaSet schemaSet = new XmlSchemaSet();
        schemaSet.Add("urn:bookstore-schema", "books.xsd");

        //Validate the file using the schema stored in the schema set.
        //Any elements belonging to the namespace "urn:cd-schema" generate
        //a warning because there is no schema matching that namespace.
        Validate("store.xml", schemaSet);
        Console.ReadLine();
    }

    private static void Validate(String filename, XmlSchemaSet schemaSet)
    {
        Console.WriteLine();
        Console.WriteLine("\r\nValidating XML file {0}...", filename.ToString());

        XmlSchema compiledSchema = null;

        foreach (XmlSchema schema in schemaSet.Schemas())
        {
            compiledSchema = schema;
        }

        XmlReaderSettings settings = new XmlReaderSettings();
        settings.Schemas.Add(compiledSchema);
        settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
        settings.ValidationType = ValidationType.Schema;

        //Create the schema validating reader.
        XmlReader vreader = XmlReader.Create(filename, settings);

        while (vreader.Read()) { }

        //Close the reader.
        vreader.Close();
    }

    //Display any warnings or errors.
    private static void ValidationCallBack(object sender, ValidationEventArgs args)
    {
        if (args.Severity == XmlSeverityType.Warning)
            Console.WriteLine("\tWarning: Matching schema not found.  No validation occurred." + args.Message);
        else
            Console.WriteLine("\tValidation error: " + args.Message);

    }
}

The preceding example uses the following input files.

<?xml version='1.0'?>
<bookstore xmlns="urn:bookstore-schema" xmlns:cd="urn:cd-schema">
  <book genre="novel">
    <title>The Confidence Man</title>
    <price>11.99</price>
  </book>
  <cd:cd>
    <title>Americana</title>
    <cd:artist>Offspring</cd:artist>
    <price>16.95</price>
  </cd:cd>
</bookstore>

books.xsd

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns="urn:bookstore-schema"
    elementFormDefault="qualified"
    targetNamespace="urn:bookstore-schema">

 <xsd:element name="bookstore" type="bookstoreType"/>

 <xsd:complexType name="bookstoreType">
  <xsd:sequence maxOccurs="unbounded">
   <xsd:element name="book"  type="bookType"/>
  </xsd:sequence>
 </xsd:complexType>

 <xsd:complexType name="bookType">
  <xsd:sequence>
   <xsd:element name="title" type="xsd:string"/>
   <xsd:element name="author" type="authorName"/>
   <xsd:element name="price"  type="xsd:decimal"/>
  </xsd:sequence>
  <xsd:attribute name="genre" type="xsd:string"/>
 </xsd:complexType>

 <xsd:complexType name="authorName">
  <xsd:sequence>
   <xsd:element name="first-name"  type="xsd:string"/>
   <xsd:element name="last-name" type="xsd:string"/>
  </xsd:sequence>
 </xsd:complexType>

</xsd:schema>

Google OAuth 2 authorization - Error: redirect_uri_mismatch

In any flow where you retrieved an authorization code on the client side, such as the GoogleAuth.grantOfflineAccess() API, and now you want to pass the code to your server, redeem it, and store the access and refresh tokens, then you have to use the literal string postmessage instead of the redirect_uri.

For example, building on the snippet in the Ruby doc:

client_secrets = Google::APIClient::ClientSecrets.load('client_secrets.json')
auth_client = client_secrets.to_authorization
auth_client.update!(
  :scope => 'profile https://www.googleapis.com/auth/drive.metadata.readonly',
  :redirect_uri => 'postmessage' # <---- HERE
)

# Inject user's auth_code here:
auth_client.code = "4/lRCuOXzLMIzqrG4XU9RmWw8k1n3jvUgsI790Hk1s3FI"
tokens = auth_client.fetch_access_token!
# { "access_token"=>..., "expires_in"=>3587, "id_token"=>..., "refresh_token"=>..., "token_type"=>"Bearer"}

The only Google documentation to even mention postmessage is this old Google+ sign-in doc. Here's a screenshot and archive link since G+ is closing and this link will likely go away:

Legacy Google+ API DOC

It is absolutely unforgivable that the doc page for Offline Access doesn't mention this. #FacePalm

How to find count of Null and Nan values for each column in a PySpark dataframe efficiently?

Here is my one liner. Here 'c' is the name of the column

df.select('c').withColumn('isNull_c',F.col('c').isNull()).where('isNull_c = True').count()

Remove Safari/Chrome textinput/textarea glow

I experienced this on a div that had a click event and after 20 some searches I found this snippet that saved my day.

-webkit-tap-highlight-color: rgba(0,0,0,0);

This disables the default button highlighting in webkit mobile browsers

How to use if - else structure in a batch file?

A little bit late and perhaps still good for complex if-conditions, because I would like to add a "done" parameter to keep a if-then-else structure:

set done=0
if %F%==1 if %C%==0 (set done=1 & echo found F=1 and C=0: %F% + %C%)
if %F%==2 if %C%==0 (set done=1 & echo found F=2 and C=0: %F% + %C%)
if %F%==3 if %C%==0 (set done=1 & echo found F=3 and C=0: %F% + %C%)
if %done%==0 (echo do something)

Create component to specific module with Angular-CLI

To create a component as part of a module you should

  1. ng g module newModule to generate a module,
  2. cd newModule to change directory into the newModule folder
  3. ng g component newComponent to create a component as a child of the module.

UPDATE: Angular 9

Now it doesn't matter what folder you are in when generating the component.

  1. ng g module NewMoudle to generate a module.
  2. ng g component new-module/new-component to create NewComponent.

Note: When the Angular CLI sees new-module/new-component, it understands and translates the case to match new-module -> NewModule and new-component -> NewComponent. It can get confusing in the beginning, so easy way is to match the names in #2 with the folder names for the module and component.

How to Empty Caches and Clean All Targets Xcode 4 and later

I have been pulling out hair from my head because I thought that I had the same problem. When building the app I didn't get the same result on my iPhone as on the simulator.

The problem was that I had somehow made a localized version of the MainStoryboard.storyboard file. So when I ran the app on my phone it showed the danish version... and the simulator showed the english version.

Yeah I'm new! :)

Why is vertical-align: middle not working on my span or div?

Setting the line-height to the same height as it's containing div will also work

DEMO http://jsfiddle.net/kevinPHPkevin/gZXWC/7/

.inner {
    line-height:72px;
    border: 1px solid #000000;
}

How to group subarrays by a column value?

function array_group_by($arr, array $keys) {

if (!is_array($arr)) {
    trigger_error('array_group_by(): The first argument should be an array', E_USER_ERROR);
}
if (count($keys)==0) {
    trigger_error('array_group_by(): The Second argument Array can not be empty', E_USER_ERROR);
}

// Load the new array, splitting by the target key
$grouped = [];
foreach ($arr as $value) {
    $grouped[$value[$keys[0]]][] = $value;
}

// Recursively build a nested grouping if more parameters are supplied
// Each grouped array value is grouped according to the next sequential key
if (count($keys) > 1) {
        foreach ($grouped as $key => $value) {
       $parms = array_merge([$value], [array_slice($keys, 1,count($keys))]);
       $grouped[$key] = call_user_func_array('array_group_by', $parms);

    }
}
return $grouped;

}

how to bind img src in angular 2 in ngFor?

Angular 2.x to 8 Compatible!

You can directly give the source property of the current object in the img src attribute. Please see my code below:

<div *ngFor="let brochure of brochureList">
    <img class="brochure-poster" [src]="brochure.imageUrl" />
</div>

NOTE: You can as well use string interpolation but that is not a legit way to do it. Property binding was created for this very purpose hence better use this.

NOT RECOMMENDED :

<img class="brochure-poster" src="{{brochure.imageUrl}}"/>

Its because that defeats the purpose of property binding. It is more meaningful to use that for setting the properties. {{}} is a normal string interpolation expression, that does not reveal to anyone reading the code that it makes special meaning. Using [] makes it easily to spot the properties that are set dynamically.

Here is my brochureList contains the following json received from service(you can assign it to any variable):

[ {
            "productId":1,
            "productName":"Beauty Products",
            "productCode": "XXXXXX",            
            "description":  "Skin Care",           
            "imageUrl":"app/Images/c1.jpg"
         },
        {
             "productId":2,
            "productName":"Samsung Galaxy J5",
            "productCode": "MOB-124",      
            "description":  "8GB, Gold",
            "imageUrl":"app/Images/c8.jpg"
         }]

What is the best way to compare floats for almost-equality in Python?

Useful for the case where you want to make sure 2 numbers are the same 'up to precision', no need to specify the tolerance:

  • Find minimum precision of the 2 numbers

  • Round both of them to minimum precision and compare

def isclose(a,b):                                       
    astr=str(a)                                         
    aprec=len(astr.split('.')[1]) if '.' in astr else 0 
    bstr=str(b)                                         
    bprec=len(bstr.split('.')[1]) if '.' in bstr else 0 
    prec=min(aprec,bprec)                                      
    return round(a,prec)==round(b,prec)                               

As written, only works for numbers without the 'e' in their string representation ( meaning 0.9999999999995e-4 < number <= 0.9999999999995e11 )

Example:

>>> isclose(10.0,10.049)
True
>>> isclose(10.0,10.05)
False

Convert datetime to valid JavaScript date

This works everywhere including Safari 5 and Firefox 5 on OS X.

UPDATE: Fx Quantum (54) has no need for the replace, but Safari 11 is still not happy unless you convert as below

_x000D_
_x000D_
var date_test = new Date("2011-07-14 11:23:00".replace(/-/g,"/"));_x000D_
console.log(date_test);
_x000D_
_x000D_
_x000D_


FIDDLE

What is mapDispatchToProps?

It's basically a shorthand. So instead of having to write:

this.props.dispatch(toggleTodo(id));

You would use mapDispatchToProps as shown in your example code, and then elsewhere write:

this.props.onTodoClick(id);

or more likely in this case, you'd have that as the event handler:

<MyComponent onClick={this.props.onTodoClick} />

There's a helpful video by Dan Abramov on this here: https://egghead.io/lessons/javascript-redux-generating-containers-with-connect-from-react-redux-visibletodolist

How to get 2 digit year w/ Javascript?

var d = new Date();
var n = d.getFullYear();

Yes, n will give you the 4 digit year, but you can always use substring or something similar to split up the year, thus giving you only two digits:

var final = n.toString().substring(2);

This will give you the last two digits of the year (2013 will become 13, etc...)

If there's a better way, hopefully someone posts it! This is the only way I can think of. Let us know if it works!

Border for an Image view in Android?

For those who are searching custom border and shape of ImageView. You can use android-shape-imageview

image

Just add compile 'com.github.siyamed:android-shape-imageview:0.9.+@aar' to your build.gradle.

And use in your layout.

<com.github.siyamed.shapeimageview.BubbleImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/neo"
    app:siArrowPosition="right"
    app:siSquare="true"/>

How do I hide certain files from the sidebar in Visual Studio Code?

For .meta files while using Unity3D, I found the best pattern for hiding is:

"files.exclude": {
  "*/**/**.meta": true
}

This captures all folders and subfolders, and will pick up foo.cs.meta in addition to foo.meta

ssh-copy-id no identities found error

Run following command

# ssh-add

If it gives following error: Could not open a connection to your authentication agent

To remove this error, Run following command:

# eval `ssh-agent`

Switch to another branch without changing the workspace files

git fetch && git checkout branch_name( "branch_name" here is the name of the branch )

Then you will see message, Switched to a new branch 'branch_name' Branch 'branch_name' set up to track remote branch 'branch_name' from 'origin'.

How to merge two arrays in JavaScript and de-duplicate items

Built a tester to check just how fast some of the performance oriented answers are. Feel free to add some more. So far, Set is both the simplest and fastest option (by bigger margins as the number of records increases), at least with simple Number types.

_x000D_
_x000D_
const records = 10000, //max records per array
  max_int = 100, //max integer value per array
  dup_rate = .5; //rate of duplication
let perf = {}, //performance logger,
  ts = 0,
  te = 0,
  array1 = [], //init arrays
  array2 = [],
  array1b = [],
  array2b = [],
  a = [];

//populate randomized arrays
for (let i = 0; i < records; i++) {
  let r = Math.random(),
    n = r * max_int;
  if (Math.random() < .5) {
    array1.push(n);
    r < dup_rate && array2.push(n);
  } else {
    array2.push(n);
    r < dup_rate && array1.push(n);
  }
}
//simple deep copies short of rfdc, in case someone wants to test with more complex data types
array1b = JSON.parse(JSON.stringify(array1));
array2b = JSON.parse(JSON.stringify(array2));
console.log('Records in Array 1:', array1.length, array1b.length);
console.log('Records in Array 2:', array2.length, array2b.length);

//test method 1 (jsperf per @Pitouli)
ts = performance.now();
for (let i = 0; i < array2.length; i++)
  if (array1.indexOf(array2[i]) === -1)
    array1.push(array2[i]); //modifies array1
te = performance.now();
perf.m1 = te - ts;
console.log('Method 1 merged', array1.length, 'records in:', perf.m1);
array1 = JSON.parse(JSON.stringify(array1b)); //reset array1

//test method 2 (classic forEach)
ts = performance.now();
array2.forEach(v => array1.includes(v) ? null : array1.push(v)); //modifies array1
te = performance.now();
perf.m2 = te - ts;
console.log('Method 2 merged', array1.length, 'records in:', perf.m2);

//test method 3 (Simplest native option)
ts = performance.now();
a = [...new Set([...array1, ...array2])]; //does not modify source arrays
te = performance.now();
perf.m3 = te - ts;
console.log('Method 3 merged', a.length, 'records in:', perf.m3);

//test method 4 (Selected Answer)
ts = performance.now();
a = array1.concat(array2); //does not modify source arrays
for (let i = 0; i < a.length; ++i) {
  for (let j = i + 1; j < a.length; ++j) {
    if (a[i] === a[j])
      a.splice(j--, 1);
  }
}
te = performance.now();
perf.m4 = te - ts;
console.log('Method 4 merged', a.length, 'records in:', perf.m4);

//test method 5 (@Kamil Kielczewski)
ts = performance.now();

function K(arr1, arr2) {
  let r = [],
    h = {};

  while (arr1.length) {
    let e = arr1.shift(); //modifies array1
    if (!h[e]) h[e] = 1 && r.push(e);
  }

  while (arr2.length) {
    let e = arr2.shift(); //modifies array2
    if (!h[e]) h[e] = 1 && r.push(e);
  }

  return r;
}
a = K(array1, array2);
te = performance.now();
perf.m5 = te - ts;
console.log('Method 5 merged', a.length, 'records in:', perf.m4);
array1 = JSON.parse(JSON.stringify(array1b)); //reset array1
array2 = JSON.parse(JSON.stringify(array2b)); //reset array2


for (let i = 1; i < 6; i++) {
  console.log('Method:', i, 'speed is', (perf['m' + i] / perf.m1 * 100).toFixed(2), '% of Method 1');
}
_x000D_
_x000D_
_x000D_

Generic type conversion FROM string

Check the static Nullable.GetUnderlyingType. - If the underlying type is null, then the template parameter is not Nullable, and we can use that type directly - If the underlying type is not null, then use the underlying type in the conversion.

Seems to work for me:

public object Get( string _toparse, Type _t )
{
    // Test for Nullable<T> and return the base type instead:
    Type undertype = Nullable.GetUnderlyingType(_t);
    Type basetype = undertype == null ? _t : undertype;
    return Convert.ChangeType(_toparse, basetype);
}

public T Get<T>(string _key)
{
    return (T)Get(_key, typeof(T));
}

public void test()
{
    int x = Get<int>("14");
    int? nx = Get<Nullable<int>>("14");
}

The correct way to read a data file into an array

I like...

@data = `cat /var/tmp/somefile`;

It's not as glamorous as others, but, it works all the same. And...

$todays_data = '/var/tmp/somefile' ;
open INFILE, "$todays_data" ; 
@data = <INFILE> ; 
close INFILE ;

Cheers.

Quoting backslashes in Python string literals

What Harley said, except the last point - it's not actually necessary to change the '/'s into '\'s before calling open. Windows is quite happy to accept paths with forward slashes.

infile = open('c:/folder/subfolder/file.txt')

The only time you're likely to need the string normpathed is if you're passing to to another program via the shell (using os.system or the subprocess module).

Flatten List in LINQ

With query syntax:

var values =
from inner in outer
from value in inner
select value;

How do I put an image into my picturebox using ImageLocation?

Setting the image using picture.ImageLocation() works fine, but you are using a relative path. Check your path against the location of the .exe after it is built.

For example, if your .exe is located at:

<project folder>/bin/Debug/app.exe

The image would have to be at:

<project folder>/bin/Image/1.jpg


Of course, you could just set the image at design-time (the Image property on the PictureBox property sheet).

If you must set it at run-time, one way to make sure you know the location of the image is to add the image file to your project. For example, add a new folder to your project, name it Image. Right-click the folder, choose "Add existing item" and browse to your image (be sure the file filter is set to show image files). After adding the image, in the property sheet set the Copy to Output Directory to Copy if newer.

At this point the image file will be copied when you build the application and you can use

picture.ImageLocation = @"Image\1.jpg"; 

How to find the privileges and roles granted to a user in Oracle?

SELECT * 
FROM DBA_ROLE_PRIVS 
WHERE UPPER(GRANTEE) LIKE '%XYZ%';

[Vue warn]: Cannot find element

You can solve it in two ways.

  1. Make sure you put the CDN into the end of html page and place your own script after that. Example:
    <body>
      <div id="main">
        <div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
      </div>
    </body>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
    <script src="js/app.js"></script>

where you need to put same javascript code you wrote in any other JavaScript file or in html file.

  1. Use window.onload function in your JavaScript file.

How to collapse blocks of code in Eclipse?

In CFEclipse: Preferences > CFEclipse > Editor > Code Folding > Initially Collapse column, you can uncheck to see all expanded when opening, or check all boxes to close all when opening a file.

findAll() in yii

Use the below code. This should work.

$comments = EmailArchive::find()->where(['email_id' => $id])->all();

How to get JSON from URL in JavaScript?

ES8(2017) try

obj = await (await fetch(url)).json();

_x000D_
_x000D_
async function load() {_x000D_
    let url = 'https://my-json-server.typicode.com/typicode/demo/db';_x000D_
    let obj = await (await fetch(url)).json();_x000D_
    console.log(obj);_x000D_
}_x000D_
_x000D_
load();
_x000D_
_x000D_
_x000D_

you can handle errors by try-catch

_x000D_
_x000D_
async function load() {_x000D_
    let url = 'http://query.yahooapis.com/v1/publ...';_x000D_
    let obj = null;_x000D_
    _x000D_
    try {_x000D_
        obj = await (await fetch(url)).json();_x000D_
    } catch(e) {_x000D_
        console.log('error');_x000D_
    }_x000D_
    _x000D_
    console.log(obj);_x000D_
}_x000D_
_x000D_
load();
_x000D_
_x000D_
_x000D_

How can I save multiple documents concurrently in Mongoose/Node.js?

Use insertMany function to insert many documents. This sends only one operation to the server and Mongoose validates all the documents before hitting the mongo server. By default Mongoose inserts item in the order they exist in the array. If you are ok with not maintaining any order then set ordered:false.

Important - Error handling:

When ordered:true validation and error handling happens in a group means if one fails everything will fail.

When ordered:false validation and error handling happens individually and operation will be continued. Error will be reported back in an array of errors.

How can I get a list of users from active directory?

If you are new to Active Directory, I suggest you should understand how Active Directory stores data first.

Active Directory is actually a LDAP server. Objects stored in LDAP server are stored hierarchically. It's very similar to you store your files in your file system. That's why it got the name Directory server and Active Directory

The containers and objects on Active Directory can be specified by a distinguished name. The distinguished name is like this CN=SomeName,CN=SomeDirectory,DC=yourdomain,DC=com. Like a traditional relational database, you can run query against a LDAP server. It's called LDAP query.

There are a number of ways to run a LDAP query in .NET. You can use DirectorySearcher from System.DirectoryServices or SearchRequest from System.DirectoryServices.Protocol.

For your question, since you are asking to find user principal object specifically, I think the most intuitive way is to use PrincipalSearcher from System.DirectoryServices.AccountManagement. You can easily find a lot of different examples from google. Here is a sample that is doing exactly what you are asking for.

using (var context = new PrincipalContext(ContextType.Domain, "yourdomain.com"))
{
    using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
    {
        foreach (var result in searcher.FindAll())
        {
            DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
            Console.WriteLine("First Name: " + de.Properties["givenName"].Value);
            Console.WriteLine("Last Name : " + de.Properties["sn"].Value);
            Console.WriteLine("SAM account name   : " + de.Properties["samAccountName"].Value);
            Console.WriteLine("User principal name: " + de.Properties["userPrincipalName"].Value);
            Console.WriteLine();
        }
    }
}
Console.ReadLine();

Note that on the AD user object, there are a number of attributes. In particular, givenName will give you the First Name and sn will give you the Last Name. About the user name. I think you meant the user logon name. Note that there are two logon names on AD user object. One is samAccountName, which is also known as pre-Windows 2000 user logon name. userPrincipalName is generally used after Windows 2000.

How to display image from database using php

instead of print $image; you should go for print "<img src=<?$image;?>>"

and note that $image should contain the path of your image.

So, If you are only storing the name of your image in database then instead of that you have to store the full path of your image in the database like /root/user/Documents/image.jpeg.

Convert file: Uri to File in Android

@CommonsWare explained all things quite well. And we really should use the solution he proposed.

By the way, only information we could rely on when querying ContentResolver is a file's name and size as mentioned here: Retrieving File Information | Android developers

As you could see there is an interface OpenableColumns that contains only two fields: DISPLAY_NAME and SIZE.

In my case I was need to retrieve EXIF information about a JPEG image and rotate it if needed before sending to a server. To do that I copied a file content into a temporary file using ContentResolver and openInputStream()

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

Are you looking for the PropertyOverrideConfigurer documented here

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

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

AngularJS : The correct way of binding to a service properties

From my perspective, $watch would be the best practice way.

You can actually simplify your example a bit:

function TimerCtrl1($scope, Timer) {
  $scope.$watch( function () { return Timer.data; }, function (data) {
    $scope.lastUpdated = data.lastUpdated;
    $scope.calls = data.calls;
  }, true);
}

That's all you need.

Since the properties are updated simultaneously, you only need one watch. Also, since they come from a single, rather small object, I changed it to just watch the Timer.data property. The last parameter passed to $watch tells it to check for deep equality rather than just ensuring that the reference is the same.


To provide a little context, the reason I would prefer this method to placing the service value directly on the scope is to ensure proper separation of concerns. Your view shouldn't need to know anything about your services in order to operate. The job of the controller is to glue everything together; its job is to get the data from your services and process them in whatever way necessary and then to provide your view with whatever specifics it needs. But I don't think its job is to just pass the service right along to the view. Otherwise, what's the controller even doing there? The AngularJS developers followed the same reasoning when they chose not to include any "logic" in the templates (e.g. if statements).

To be fair, there are probably multiple perspectives here and I look forward to other answers.

How can I compile my Perl script so it can be executed on systems without perl installed?

pp can create an executable that includes perl and your script (and any module dependencies), but it will be specific to your architecture, so you couldn't run it on both Windows and linux for instance.

From its doc:

To make a stand-alone executable, suitable for running on a machine that doesn't have perl installed:

   % pp -o packed.exe source.pl        # makes packed.exe
   # Now, deploy 'packed.exe' to target machine...
   $ packed.exe                        # run it

(% and $ there are command prompts on different machines).

Store mysql query output into a shell variable

If you have particular database name and a host on which you want the query to be executed then follow below query:

outputofquery=$(mysql -u"$dbusername" -p"$dbpassword" -h"$dbhostname" -e "SELECT A, B, C FROM table_a;" $dbname)

So to run the mysql queries you need to install mysql client on linux

Why is Thread.Sleep so harmful

For those of you who hasn't seen one valid argument against use of Thread.Sleep in SCENARIO 2, there really is one - application exit be held up by the while loop (SCENARIO 1/3 is just plain stupid so not worthy of more mentioning)

Many who pretend to be in-the-know, screaming Thread.Sleep is evil failed to mentioned a single valid reason for those of us who demanded a practical reason not to use it - but here it is, thanks to Pete - Thread.Sleep is Evil (can be easily avoided with a timer/handler)

    static void Main(string[] args)
    {
        Thread t = new Thread(new ThreadStart(ThreadFunc));
        t.Start();

        Console.WriteLine("Hit any key to exit.");
        Console.ReadLine();

        Console.WriteLine("App exiting");
        return;
    }

    static void ThreadFunc()
    {
        int i=0;
        try
        {
            while (true)
            {
                Console.WriteLine(Thread.CurrentThread.ThreadState.ToString() + " " + i);

                Thread.Sleep(1000 * 10);
                i++;
            }
        }
        finally
        {
            Console.WriteLine("Exiting while loop");
        }
        return;
    }

Regular Expression to match string starting with a specific word

I'd advise against a simple regular expression approach to this problem. There are too many words that are substrings of other unrelated words, and you'll probably drive yourself crazy trying to overadapt the simpler solutions already provided.

You'll want at least a naive stemming algorithm (try the Porter stemmer; there's available, free code in most languages) to process text first. Keep this processed text and the preprocessed text in two separate space-split arrays. Make sure each non-alphabetical character also gets its own index in this array. Whatever list of words you're filtering, stem them also.

The next step would be to find the array indices which match to your list of stemmed 'stop' words. Remove those from the unprocessed array, and then rejoin on spaces.

This is only slightly more complicated, but will be much more reliable an approach. If you've got any doubts on the value of a more NLP-oriented approach, you might want to do some research into clbuttic mistakes.

GIT_DISCOVERY_ACROSS_FILESYSTEM not set

ran across this page and several like it all talking about the GIT_DISCOVERY_ACROSS_FILESYSTEM not set message. In my case our sys admin had decided that the apache2 directory needed to be on a mounted filesystem in case the disk for the server stopped working and had to get rebuilt. I found this with a simple df command:

-->  UBIk  <--:root@ns1:[/etc]
--PRODUCTION--(16:48:43)--> df -h
Filesystem                           Size  Used Avail Use% Mounted on
<snip>
/dev/mapper/vgraid-lvapache           63G   54M   60G   1% /etc/apache2
<snip>

To fix this I just put the following in the root user's shell (as they are the only ones who need to be looking at etckeeper revisions:

export GIT_DISCOVERY_ACROSS_FILESYSTEM=1

and all was well and good...much joy.

More notes:

-->  UBIk  <--:root@ns1:[/etc]
--PRODUCTION--(16:48:54)--> export GIT_DISCOVERY_ACROSS_FILESYSTEM=0

-->  UBIk  <--:root@ns1:[/etc]
--PRODUCTION--(16:57:35)--> git status
On branch master
nothing to commit, working tree clean

-->  UBIk  <--:root@ns1:[/etc]
--PRODUCTION--(16:57:40)--> touch apache2/me

-->  UBIk  <--:root@ns1:[/etc]
--PRODUCTION--(16:57:45)--> git status
On branch master
Untracked files:
  (use "git add <file>..." to include in what will be committed)

    apache2/me

nothing added to commit but untracked files present (use "git add" to track)

-->  UBIk  <--:root@ns1:[/etc]
--PRODUCTION--(16:57:47)--> cd apache2

-->  UBIk  <--:root@ns1:[/etc/apache2]
--PRODUCTION--(16:57:50)--> git status
fatal: Not a git repository (or any parent up to mount point /etc/apache2)
Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).
-->  UBIk  <--:root@ns1:[/etc/apache2]
--PRODUCTION--(16:57:52)--> export GIT_DISCOVERY_ACROSS_FILESYSTEM=1

-->  UBIk  <--:root@ns1:[/etc/apache2]
--PRODUCTION--(16:58:59)--> git status
On branch master
Untracked files:
  (use "git add <file>..." to include in what will be committed)

    me

nothing added to commit but untracked files present (use "git add" to track)

Hopefully that will help someone out somewhere... -wc

Pass arguments into C program from command line

In C, this is done using arguments passed to your main() function:

int main(int argc, char *argv[])
{
    int i = 0;
    for (i = 0; i < argc; i++) {
        printf("argv[%d] = %s\n", i, argv[i]);
    }
    return 0;
}

More information can be found online such as this Arguments to main article.

How can I convert a date to GMT?

You can simply use the toUTCString (or toISOString) methods of the date object.

Example:

new Date("Fri Jan 20 2012 11:51:36 GMT-0500").toUTCString()

// Output:  "Fri, 20 Jan 2012 16:51:36 GMT"

If you prefer better control of the output format, consider using a library such as date-fns or moment.js.

Also, in your question, you've actually converted the time incorrectly. When an offset is shown in a timestamp string, it means that the date and time values in the string have already been adjusted from UTC by that value. To convert back to UTC, invert the sign before applying the offset.

11:51:36 -0300  ==  14:51:36Z

How should I edit an Entity Framework connection string?

No, you can't edit the connection string in the designer. The connection string is not part of the EDMX file it is just referenced value from the configuration file and probably because of that it is just readonly in the properties window.

Modifying configuration file is common task because you sometimes wants to make change without rebuilding the application. That is the reason why configuration files exist.

How to copy an object by value, not by reference

Can't you just make a copy constructor? By the way Java always passes references by value, so you keep pointing to the same object.

What is the meaning of "int(a[::-1])" in Python?

Assuming a is a string. The Slice notation in python has the syntax -

list[<start>:<stop>:<step>]

So, when you do a[::-1], it starts from the end towards the first taking each element. So it reverses a. This is applicable for lists/tuples as well.

Example -

>>> a = '1234'
>>> a[::-1]
'4321'

Then you convert it to int and then back to string (Though not sure why you do that) , that just gives you back the string.

How to create a JSON object

You just need another layer in your php array:

$post_data = array(
  'item' => array(
    'item_type_id' => $item_type,
    'string_key' => $string_key,
    'string_value' => $string_value,
    'string_extra' => $string_extra,
    'is_public' => $public,
   'is_public_for_contacts' => $public_contacts
  )
);

echo json_encode($post_data);

Java Date - Insert into database

Granted, PreparedStatement will make your code better, but to answer your question you need to tell the DBMS the format of your string representation of the Date. In Oracle (you don't name your database vendor) a string date is converted to Date using the TO_DATE() function:

INSERT INTO TABLE_NAME(
  date_column
)values(
  TO_DATE('06/06/2006', 'mm/dd/yyyy')
)

CSS to make table 100% of max-width

Like this

demo

css

table{
    width:100%;
}

How to programmatically connect a client to a WCF service?

You'll have to use the ChannelFactory class.

Here's an example:

var myBinding = new BasicHttpBinding();
var myEndpoint = new EndpointAddress("http://localhost/myservice");
using (var myChannelFactory = new ChannelFactory<IMyService>(myBinding, myEndpoint))
{
    IMyService client = null;

    try
    {
        client = myChannelFactory.CreateChannel();
        client.MyServiceOperation();
        ((ICommunicationObject)client).Close();
        myChannelFactory.Close();
    }
    catch
    {
        (client as ICommunicationObject)?.Abort();
    }
}

Related resources:

Add / Change parameter of URL and redirect to the new URL

I had a similar situation where I wanted to replace a URL query parameter. However, I only had one param, and I could simply replace it:

window.location.search = '?filter=' + my_filter_value

The location.search property allows you to get or set the query portion of a URL.

How to programmatically take a screenshot on Android?

For Full Page Scrolling Screenshot

If you want to capture a full View screenshot (Which contains a scrollview or so) then have a check at this library

https://github.com/peter1492/LongScreenshot

All you have to do is import the Gradel, and create an object of BigScreenshot

BigScreenshot longScreenshot = new BigScreenshot(this, x, y);

A callback will be received with the bitmap of the Screenshots taken while automatically scrolling through the screen view group and at the end assembled together.

@Override public void getScreenshot(Bitmap bitmap) {}

Which can be saved to the gallery or whatsoever usage is necessary their after

How can I convert a char to int in Java?

You can use static methods from Character class to get Numeric value from char.

char x = '9';

if (Character.isDigit(x)) { // Determines if the specified character is a digit.
    int y = Character.getNumericValue(x); //Returns the int value that the 
                                          //specified Unicode character represents.
    System.out.println(y);
}

@selector() in Swift?

Change as a simple string naming in the method calling for selector syntax

var timer1 : NSTimer? = nil
timer1= NSTimer(timeInterval: 0.1, target: self, selector: Selector("test"), userInfo: nil, repeats: true)

After that, type func test().

.htaccess file to allow access to images folder to view pictures?

Give permission in .htaccess as follows:

<Directory "Your directory path/uploads/">
Allow from all
</Directory>

HTML: Select multiple as dropdown

A similar question was asked here

If you're able to add an external library to your project, you can try Chosen

Here's a sample:

_x000D_
_x000D_
$(".chosen-select").chosen({_x000D_
  no_results_text: "Oops, nothing found!"_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdn.rawgit.com/harvesthq/chosen/gh-pages/chosen.jquery.min.js"></script>_x000D_
<link href="https://cdn.rawgit.com/harvesthq/chosen/gh-pages/chosen.min.css" rel="stylesheet"/>_x000D_
_x000D_
<form action="http://httpbin.org/post" method="post">_x000D_
  <select data-placeholder="Begin typing a name to filter..." multiple class="chosen-select" name="test">_x000D_
    <option value=""></option>_x000D_
    <option>American Black Bear</option>_x000D_
    <option>Asiatic Black Bear</option>_x000D_
    <option>Brown Bear</option>_x000D_
    <option>Giant Panda</option>_x000D_
    <option>Sloth Bear</option>_x000D_
    <option>Sun Bear</option>_x000D_
    <option>Polar Bear</option>_x000D_
    <option>Spectacled Bear</option>_x000D_
  </select>_x000D_
  <input type="submit">_x000D_
</form>
_x000D_
_x000D_
_x000D_

One thing I've run into, you have to include JQuery BEFORE you include Chosen or you'll get errors.

Automatic exit from Bash shell script on error

Use the set -e builtin:

#!/bin/bash
set -e
# Any subsequent(*) commands which fail will cause the shell script to exit immediately

Alternatively, you can pass -e on the command line:

bash -e my_script.sh

You can also disable this behavior with set +e.

You may also want to employ all or some of the the -e -u -x and -o pipefail options like so:

set -euxo pipefail

-e exits on error, -u errors on undefined variables, and -o (for option) pipefail exits on command pipe failures. Some gotchas and workarounds are documented well here.

(*) Note:

The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test following the if or elif reserved words, part of any command executed in a && or || list except the command following the final && or ||, any command in a pipeline but the last, or if the command's return value is being inverted with !

(from man bash)

C++ compile time error: expected identifier before numeric constant

You cannot do this:

vector<string> name(5); //error in these 2 lines
vector<int> val(5,0);

in a class outside of a method.

You can initialize the data members at the point of declaration, but not with () brackets:

class Foo {
    vector<string> name = vector<string>(5);
    vector<int> val{vector<int>(5,0)};
};

Before C++11, you need to declare them first, then initialize them e.g in a contructor

class Foo {
    vector<string> name;
    vector<int> val;
 public:
  Foo() : name(5), val(5,0) {}
};

How can I use goto in Javascript?

Generally, I'd prefer not using GoTo for bad readability. To me, it's a bad excuse for programming simple iterative functions instead of having to program recursive functions, or even better (if things like a Stack Overflow is feared), their true iterative alternatives (which may sometimes be complex).

Something like this would do:

while(true) {
   alert("RINSE");
   alert("LATHER");
}

That right there is an infinite loop. The expression ("true") inside the parantheses of the while clause is what the Javascript engine will check for - and if the expression is true, it'll keep the loop running. Writing "true" here always evaluates to true, hence an infinite loop.

Convert String to Double - VB

VB.NET Sample Code

Dim A as String = "5.3"
Dim B as Double

B = CDbl(Val(A)) '// Val do hard work

'// Get output 
MsgBox (B) '// Output is 5,3 Without Val result is 53.0

Regex for string contains?

Assuming regular PCRE-style regex flavors:

If you want to check for it as a single, full word, it's \bTest\b, with appropriate flags for case insensitivity if desired and delimiters for your programming language. \b represents a "word boundary", that is, a point between characters where a word can be considered to start or end. For example, since spaces are used to separate words, there will be a word boundary on either side of a space.

If you want to check for it as part of the word, it's just Test, again with appropriate flags for case insensitivity. Note that usually, dedicated "substring" methods tend to be faster in this case, because it removes the overhead of parsing the regex.

How do I prevent mails sent through PHP mail() from going to spam?

<?php 
$to1 = '[email protected]';
$subject = 'Tester subject'; 

    // To send HTML mail, the Content-type header must be set

    $headers .= "Reply-To: The Sender <[email protected]>\r\n"; 
    $headers .= "Return-Path: The Sender <[email protected]>\r\n"; 
    $headers .= "From: [email protected]" ."\r\n" .
    $headers .= "Organization: Sender Organization\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=utf-8\r\n";
    $headers .= "X-Priority: 3\r\n";
    $headers .= "X-Mailer: PHP". phpversion() ."\r\n" ;
?>

Spring RestTemplate - how to enable full debugging/logging of requests/responses?

None of these answers actually solve 100% of the problem. mjj1409 gets most of it, but conveniently avoids the issue of logging the response, which takes a bit more work. Paul Sabou provides a solution that seems realistic, but doesn't provide enough details to actually implement (and it didn't work at all for me). Sofiene got the logging but with a critical problem: the response is no longer readable because the input stream has already been consumed!

I recommend using a BufferingClientHttpResponseWrapper to wrap the response object to allow reading the response body multiple times:

public class LoggingRequestInterceptor implements ClientHttpRequestInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(LoggingRequestInterceptor.class);

    @Override
    public ClientHttpResponse intercept(final HttpRequest request, final byte[] body,
            final ClientHttpRequestExecution execution) throws IOException {
        ClientHttpResponse response = execution.execute(request, body);

        response = log(request, body, response);

        return response;
    }

    private ClientHttpResponse log(final HttpRequest request, final byte[] body, final ClientHttpResponse response) {
        final ClientHttpResponse responseCopy = new BufferingClientHttpResponseWrapper(response);
        logger.debug("Method: ", request.getMethod().toString());
        logger.debug("URI: ", , request.getURI().toString());
        logger.debug("Request Body: " + new String(body));
        logger.debug("Response body: " + IOUtils.toString(responseCopy.getBody()));
        return responseCopy;
    }

}

This will not consume the InputStream because the response body is loaded into memory and can be read multiple times. If you do not have the BufferingClientHttpResponseWrapper on your classpath, you can find the simple implementation here:

https://github.com/spring-projects/spring-android/blob/master/spring-android-rest-template/src/main/java/org/springframework/http/client/BufferingClientHttpResponseWrapper.java

For setting up the RestTemplate:

LoggingRequestInterceptor loggingInterceptor = new LoggingRequestInterceptor();
restTemplate.getInterceptors().add(loggingInterceptor);

what is the use of fflush(stdin) in c programming

It's not in standard C, so the behavior is undefined.

Some implementation uses it to clear stdin buffer.

From C11 7.21.5.2 The fflush function, fflush works only with output/update stream, not input stream.

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

NodeJS - Error installing with NPM

Fixed with downgrading Node from v12.8.1 to v11.15.0 and everything installed successfully

using awk with column value conditions

If you're looking for a particular string, put quotes around it:

awk '$1 == "findtext" {print $3}'

Otherwise, awk will assume it's a variable name.

How to fill Matrix with zeros in OpenCV?

I presume you are talking about filling zeros of some existing mat? How about this? :)

mat *= 0;

How can I select all elements without a given class in jQuery?

if (!$(row).hasClass("changed")) {
    // do your stuff
}

source of historical stock data

I'd crawl finance.google.com (for the quotes) - or finance.yahoo.com.

Both these will return html pages for most exchanges around the world, including historical. Then, it's just a matter of parsing the HTML to extract what you need.

I've done this in the past, with great success. Alternatively, if you don't mind using Perl - there are several modules on CPAN that have done this work for you - i.e. extracting quotes from Google/Yahoo.

For more, see Quote History

CSS Div Background Image Fixed Height 100% Width

See my answer to a similar question here.

It sounds like you want a background-image to keep it's own aspect ratio while expanding to 100% width and getting cropped off on the top and bottom. If that's the case, do something like this:

.chapter {
    position: relative;
    height: 1200px;
    z-index: 1;
}

#chapter1 {
    background-image: url(http://omset.files.wordpress.com/2010/06/homer-simpson-1-264a0.jpg);
    background-repeat: no-repeat;
    background-size: 100% auto;
    background-position: center top;
    background-attachment: fixed;
}

jsfiddle: http://jsfiddle.net/ndKWN/3/

The problem with this approach is that you have the container elements at a fixed height, so there can be space below if the screen is small enough.

If you want the height to keep the image's aspect ratio, you'll have to do something like what I wrote in an edit to the answer I linked to above. Set the container's height to 0 and set the padding-bottom to the percentage of the width:

.chapter {
    position: relative;
    height: 0;
    padding-bottom: 75%;
    z-index: 1;
}

#chapter1 {
    background-image: url(http://omset.files.wordpress.com/2010/06/homer-simpson-1-264a0.jpg);
    background-repeat: no-repeat;
    background-size: 100% auto;
    background-position: center top;
    background-attachment: fixed;
}

jsfiddle: http://jsfiddle.net/ndKWN/4/

You could also put the padding-bottom percentage into each #chapter style if each image has a different aspect ratio. In order to use different aspect ratios, divide the height of the original image by it's own width, and multiply by 100 to get the percentage value.

Print an integer in binary format in Java

I needed something to print things out nicely and separate the bits every n-bit. In other words display the leading zeros and show something like this:

n = 5463
output = 0000 0000 0000 0000 0001 0101 0101 0111

So here's what I wrote:

/**
 * Converts an integer to a 32-bit binary string
 * @param number
 *      The number to convert
 * @param groupSize
 *      The number of bits in a group
 * @return
 *      The 32-bit long bit string
 */
public static String intToString(int number, int groupSize) {
    StringBuilder result = new StringBuilder();

    for(int i = 31; i >= 0 ; i--) {
        int mask = 1 << i;
        result.append((number & mask) != 0 ? "1" : "0");

        if (i % groupSize == 0)
            result.append(" ");
    }
    result.replace(result.length() - 1, result.length(), "");

    return result.toString();
}

Invoke it like this:

public static void main(String[] args) {
    System.out.println(intToString(5463, 4));
}

Angular 6: saving data to local storage

you can use localStorage for storing the json data:

the example is given below:-

let JSONDatas = [
    {"id": "Open"},
    {"id": "OpenNew", "label": "Open New"},
    {"id": "ZoomIn", "label": "Zoom In"},
    {"id": "ZoomOut", "label": "Zoom Out"},
    {"id": "Find", "label": "Find..."},
    {"id": "FindAgain", "label": "Find Again"},
    {"id": "Copy"},
    {"id": "CopyAgain", "label": "Copy Again"},
    {"id": "CopySVG", "label": "Copy SVG"},
    {"id": "ViewSVG", "label": "View SVG"}
]

localStorage.setItem("datas", JSON.stringify(JSONDatas));

let data = JSON.parse(localStorage.getItem("datas"));

console.log(data);

How do I commit case-sensitive only filename changes in Git?

Similar to @Sijmen's answer, this is what worked for me on OSX when renaming a directory (inspired by this answer from another post):

git mv CSS CSS2
git mv CSS2 css

Simply doing git mv CSS css gave the invalid argument error: fatal: renaming '/static/CSS' failed: Invalid argument perhaps because OSX's file system is case insensitive

p.s BTW if you are using Django, collectstatic also wouldn't recognize the case difference and you'd have to do the above, manually, in the static root directory as well

What is the right way to populate a DropDownList from a database?

You could bind the DropDownList to a data source (DataTable, List, DataSet, SqlDataSource, etc).

For example, if you wanted to use a DataTable:

ddlSubject.DataSource = subjectsTable;
ddlSubject.DataTextField = "SubjectNamne";
ddlSubject.DataValueField = "SubjectID";
ddlSubject.DataBind();

EDIT - More complete example

private void LoadSubjects()
{

    DataTable subjects = new DataTable();

    using (SqlConnection con = new SqlConnection(connectionString))
    {

        try
        {
            SqlDataAdapter adapter = new SqlDataAdapter("SELECT SubjectID, SubjectName FROM Students.dbo.Subjects", con);
            adapter.Fill(subjects);

            ddlSubject.DataSource = subjects;
            ddlSubject.DataTextField = "SubjectNamne";
            ddlSubject.DataValueField = "SubjectID";
            ddlSubject.DataBind();
        }
        catch (Exception ex)
        {
            // Handle the error
        }

    }

    // Add the initial item - you can add this even if the options from the
    // db were not successfully loaded
    ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));

}

To set an initial value via the markup, rather than code-behind, specify the option(s) and set the AppendDataBoundItems attribute to true:

<asp:DropDownList ID="ddlSubject" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Text="<Select Subject>" Value="0" />
</asp:DropDownList>

You could then bind the DropDownList to a DataSource in the code-behind (just remember to remove:

ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));

from the code-behind, or you'll have two "" items.

Memory address of an object in C#

Getting the address of an arbitrary object in .NET is not possible, but can be done if you change the source code and use mono. See instructions here: Get Memory Address of .NET Object (C#)

Finding the id of a parent div using Jquery

To get the id of the parent div:

$(buttonSelector).parents('div:eq(0)').attr('id');

Also, you can refactor your code quite a bit:

$('button').click( function() {
 var correct = Number($(this).attr('rel'));
 validate(Number($(this).siblings('input').val()), correct);
 $(this).parents('div:eq(0)').html(feedback);
});

Now there is no need for a button-class

explanation
eq(0), means that you will select one element from the jQuery object, in this case element 0, thus the first element. http://docs.jquery.com/Selectors/eq#index
$(selector).siblings(siblingsSelector) will select all siblings (elements with the same parent) that match the siblingsSelector http://docs.jquery.com/Traversing/siblings#expr
$(selector).parents(parentsSelector) will select all parents of the elements matched by selector that match the parent selector. http://docs.jquery.com/Traversing/parents#expr
Thus: $(selector).parents('div:eq(0)'); will match the first parent div of the elements matched by selector.

You should have a look at the jQuery docs, particularly selectors and traversing:

Find PHP version on windows command line

Nothing to worry it's easy

If you are using any local server like Wamp, Xampp then Go to this Steps

  1. Go to your drive
  2. Check xampp or wamp server that you installed
  3. Inside that check php, if you got then go for next step
  4. You will find php.exe, Once you get php.exe then you are done. Just type the path like below, here i am using XAMPP and type v for checking version and you are done.

    C:>"C:\xampp\php\php.exe" -v

Thanks.

Check that Field Exists with MongoDB

db.<COLLECTION NAME>.find({ "<FIELD NAME>": { $exists: true, $ne: null } })

Process list on Linux via Python

The sanctioned way of creating and using child processes is through the subprocess module.

import subprocess
pl = subprocess.Popen(['ps', '-U', '0'], stdout=subprocess.PIPE).communicate()[0]
print pl

The command is broken down into a python list of arguments so that it does not need to be run in a shell (By default the subprocess.Popen does not use any kind of a shell environment it just execs it). Because of this we cant simply supply 'ps -U 0' to Popen.

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

Shouldn't you add to the login form?;

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/> 

As stated in the here in the Spring security documentation

Connect to mysql on Amazon EC2 from a remote server

Solution to this is three steps:

  1. Within MySQL my.ini/ my.cnf file change the bind-address to accept connection from all hosts (0.0.0.0).

  2. Within aws console - ec2 - specific security group open your mysql port (default is 3306) to accept connections from all hosts (0.0.0.0).

  3. Within windows firewall add the mysql port (default is 3306) to exceptions.

And this will start accepting remote connections.

Declaring static constants in ES6 classes?

Maybe just put all your constants in a frozen object?

class MyClass {

    constructor() {
        this.constants = Object.freeze({
            constant1: 33,
            constant2: 2,
        });
    }

    static get constant1() {
        return this.constants.constant1;
    }

    doThisAndThat() {
        //...
        let value = this.constants.constant2;
        //...
    }
}

string to string array conversion in java

/**
 * <pre>
 * MyUtils.splitString2SingleAlphaArray(null, "") = null
 * MyUtils.splitString2SingleAlphaArray("momdad", "") = [m,o,m,d,a,d]
 * </pre>
 * @param str  the String to parse, may be null
 * @return an array of parsed Strings, {@code null} if null String input
 */
public static String[] splitString2SingleAlphaArray(String s){
    if (s == null )
        return null;
    char[] c = s.toCharArray();
    String[] sArray = new String[c.length];
    for (int i = 0; i < c.length; i++) {
        sArray[i] = String.valueOf(c[i]);
    }
    return sArray;
}

Method String.split will generate empty 1st, you have to remove it from the array. It's boring.

Uncaught ReferenceError: <function> is not defined at HTMLButtonElement.onclick

Place your script inside the body tag

<body>
  // Rest of html
  <script>
  function hideButton() {
    $(".loading").hide();
  }
function showButton() {
  $(".loading").show();
}
</script> 
< /body>

If you check this JSFIDDLE and click on javascript, you will see the load Type body is selected

Why am I getting "void value not ignored as it ought to be"?

The original poster is quoting a GCC compiler error message, but even by reading this thread, it's not clear that the error message is properly addressed - except by @pmg's answer. (+1, btw)


error: void value not ignored as it ought to be

This is a GCC error message that means the return-value of a function is 'void', but that you are trying to assign it to a non-void variable.

Example:

void myFunction()
{
   //...stuff...
}

int main()
{
   int myInt = myFunction(); //Compile error!

    return 0;
}

You aren't allowed to assign void to integers, or any other type.

In the OP's situation:

int a = srand(time(NULL));

...is not allowed. srand(), according to the documentation, returns void.

This question is a duplicate of:

I am responding, despite it being duplicates, because this is the top result on Google for this error message. Because this thread is the top result, it's important that this thread gives a succinct, clear, and easily findable result.

Ambiguous overload call to abs(double)

The header <math.h> is a C std lib header. It defines a lot of stuff in the global namespace. The header <cmath> is the C++ version of that header. It defines essentially the same stuff in namespace std. (There are some differences, like that the C++ version comes with overloads of some functions, but that doesn't matter.) The header <cmath.h> doesn't exist.

Since vendors don't want to maintain two versions of what is essentially the same header, they came up with different possibilities to have only one of them behind the scenes. Often, that's the C header (since a C++ compiler is able to parse that, while the opposite won't work), and the C++ header just includes that and pulls everything into namespace std. Or there's some macro magic for parsing the same header with or without namespace std wrapped around it or not. To this add that in some environments it's awkward if headers don't have a file extension (like editors failing to highlight the code etc.). So some vendors would have <cmath> be a one-liner including some other header with a .h extension. Or some would map all includes matching <cblah> to <blah.h> (which, through macro magic, becomes the C++ header when __cplusplus is defined, and otherwise becomes the C header) or <cblah.h> or whatever.

That's the reason why on some platforms including things like <cmath.h>, which ought not to exist, will initially succeed, although it might make the compiler fail spectacularly later on.

I have no idea which std lib implementation you use. I suppose it's the one that comes with GCC, but this I don't know, so I cannot explain exactly what happened in your case. But it's certainly a mix of one of the above vendor-specific hacks and you including a header you ought not to have included yourself. Maybe it's the one where <cmath> maps to <cmath.h> with a specific (set of) macro(s) which you hadn't defined, so that you ended up with both definitions.

Note, however, that this code still ought not to compile:

#include <cmath>

double f(double d)
{
  return abs(d);
}

There shouldn't be an abs() in the global namespace (it's std::abs()). However, as per the above described implementation tricks, there might well be. Porting such code later (or just trying to compile it with your vendor's next version which doesn't allow this) can be very tedious, so you should keep an eye on this.

Add/Delete table rows dynamically using JavaScript

This seems a lot cleaner than the answer above...

<script>
var maxID = 0;
function getTemplateRow() {
var x = document.getElementById("templateRow").cloneNode(true);
x.id = "";
x.style.display = "";
x.innerHTML = x.innerHTML.replace(/{id}/, ++maxID);
return x;
}
function addRow() {
var t = document.getElementById("theTable");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
r.parentNode.insertBefore(getTemplateRow(), r);

}
</script>


<table id="theTable">
<tr>
<td>id</td>
<td>name</td>
</tr>
<tr id="templateRow" style="display:none">
<td>{id}</td>
<td><input /></td>
</tr>
</table>


<button onclick="addRow();">Go</button>

How to stop (and restart) the Rails Server?

On OSX, you can take advantage of the UNIX-like command line - here's what I keep handy in my .bashrc to enable me to more easily restart a server that's running in background (-d) mode (note that you have to be in the Rails root directory when running this):

alias restart_rails='kill -9 `cat tmp/pids/server.pid`; rails server -d'

My initial response to the comment by @zane about how the PID file isn't removed was that it might be behavior dependent on the Rails version or OS type. However, it's also possible that the shell runs the second command (rails server -d) sooner than the kill can actually cause the previous running instance to stop.

So alternatively, kill -9 cat tmp/pids/server.pid && rails server -d might be more robust; or you can specifically run the kill, wait for the tmp/pids folder to empty out, then restart your new server.

How to run SQL script in MySQL?

You have quite a lot of options:

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

Passing Javascript variable to <a href >

If you use internationalization (i18n), and after switch to another language, something like ?locale=fror ?fr might be added at the end of the url. But when you go to another page on click event, translation switch wont be stable.

For this kind of cases a DOM click event handler function must be produced to handle all the a.href attributes by storing the switch state as a variable and add it to all a tags’ tail.

How do I ignore files in a directory in Git?

Paths which contain slashes are taken to be relative to the directory containing the .gitignore file - usually the top level of your repository, though you can also place them in subdirectories.

So, since in all of the examples you give, the paths contain slashes, the two versions are identical. The only time you need to put a leading slash is when there isn't one in the path already. For example, to ignore foo only at the top level of the repository, use /foo. Simply writing foo would ignore anything called foo anywhere in the repository.

Your wildcards are also redundant. If you want to ignore an entire directory, simply name it:

lib/model/om

The only reason to use wildcards the way you have is if you intend to subsequently un-ignore something in the directory:

lib/model/om/*      # ignore everything in the directory
!lib/model/om/foo   # except foo

jquery drop down menu closing by clicking outside

Selected answer works for one drop down menu only. For multiple solution would be:

$('body').click(function(event){
   $dropdowns.not($dropdowns.has(event.target)).hide();
});

"call to undefined function" error when calling class method

you need to call the function like this

$this->assign()

instead of just assign()

How to reload a page after the OK click on the Alert Page

Interesting that Firefox will stop further processing of JavaScript after the relocate function. Chrome and IE will continue to display any other alerts and then reload the page. Try it:

<script type="text/javascript">
    alert('foo');
    window.location.reload(true);
    alert('bar');
    window.location.reload(true);
    alert('foobar');
    window.location.reload(true);
</script>

Division in Python 2.7. and 3.3

In Python 2.x, make sure to have at least one operand of your division in float. Multiple ways you may achieve this as the following examples:

20. / 15
20 / float(15)

Read next word in java

You can just use Scanner to read word by word, Scanner.next() reads the next word

try {
  Scanner s = new Scanner(new File(filename));

  while (s.hasNext()) {
    System.out.println("word:" + s.next());
  }
} catch (IOException e) {
  System.out.println("Error accessing input file!");
}

How to concatenate strings with padding in sqlite

The || operator is "concatenate" - it joins together the two strings of its operands.

From http://www.sqlite.org/lang_expr.html

For padding, the seemingly-cheater way I've used is to start with your target string, say '0000', concatenate '0000423', then substr(result, -4, 4) for '0423'.

Update: Looks like there is no native implementation of "lpad" or "rpad" in SQLite, but you can follow along (basically what I proposed) here: http://verysimple.com/2010/01/12/sqlite-lpad-rpad-function/

-- the statement below is almost the same as
-- select lpad(mycolumn,'0',10) from mytable

select substr('0000000000' || mycolumn, -10, 10) from mytable

-- the statement below is almost the same as
-- select rpad(mycolumn,'0',10) from mytable

select substr(mycolumn || '0000000000', 1, 10) from mytable

Here's how it looks:

SELECT col1 || '-' || substr('00'||col2, -2, 2) || '-' || substr('0000'||col3, -4, 4)

it yields

"A-01-0001"
"A-01-0002"
"A-12-0002"
"C-13-0002"
"B-11-0002"

Unique on a dataframe with only selected columns

Here are a couple dplyr options that keep non-duplicate rows based on columns id and id2:

library(dplyr)                                        
df %>% distinct(id, id2, .keep_all = TRUE)
df %>% group_by(id, id2) %>% filter(row_number() == 1)
df %>% group_by(id, id2) %>% slice(1)

How to change the timeout on a .NET WebClient object

You can extend the timeout: inherit the original WebClient class and override the webrequest getter to set your own timeout, like in the following example.

MyWebClient was a private class in my case:

private class MyWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri uri)
    {
        WebRequest w = base.GetWebRequest(uri);
        w.Timeout = 20 * 60 * 1000;
        return w;
    }
}

How to make a simple modal pop up form using jquery and html?

I came across this question when I was trying similar things.

A very nice and simple sample is presented at w3schools website.

https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
  <title>Bootstrap Example</title>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
  <h2>Modal Example</h2>_x000D_
  <!-- Trigger the modal with a button -->_x000D_
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>_x000D_
_x000D_
  <!-- Modal -->_x000D_
  <div class="modal fade" id="myModal" role="dialog">_x000D_
    <div class="modal-dialog">_x000D_
    _x000D_
      <!-- Modal content-->_x000D_
      <div class="modal-content">_x000D_
        <div class="modal-header">_x000D_
          <button type="button" class="close" data-dismiss="modal">&times;</button>_x000D_
          <h4 class="modal-title">Modal Header</h4>_x000D_
        </div>_x000D_
        <div class="modal-body">_x000D_
          <p>Some text in the modal.</p>_x000D_
        </div>_x000D_
        <div class="modal-footer">_x000D_
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
        </div>_x000D_
      </div>_x000D_
      _x000D_
    </div>_x000D_
  </div>_x000D_
  _x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to remove a package in sublime text 2

Just wanted to add, that after you remove the package in question you might also need to check to see if it's listed in the list of packages in the following area and manually remove its listing:

Preferences>Package Settings>Package Control>Settings - User

{
    "auto_upgrade_last_run": null,
    "installed_packages":
    [
        "AdvancedNewFile",
        "Emmet",
        "Package Control",
        "SideBarEnhancements",
        "Sublimerge"
    ]
}

In my instance, my trial period for "Sublimerge" had run out and I would get a popup every time I would start Sublime Text 2 saying:

"The package specified, Sublimerge, is not available"

I would have to close the event window out before being able to do anything in ST2.

But in my case, even after successfully removing the package through package control, I still received a event window popup message telling me "Sublimerge" wasn't available. This didn't make any sense as I had successfully removed the package.

It wasn't until I found this "auto_upgrade_last_run" file and manually removed the "Sublimerge" entry and saved my edit, did the message go away.

Manually type in a value in a "Select" / Drop-down HTML list?

Another common solution is adding "Other.." option to the drop down and when selected show text box that is otherwise hidden. Then when submitting the form, assign hidden field value with either the drop down or textbox value and in the server side code check the hidden value.

Example: http://jsfiddle.net/c258Q/

HTML code:

Please select: <form onsubmit="FormSubmit(this);">
<input type="hidden" name="fruit" />
<select name="fruit_ddl" onchange="DropDownChanged(this);">
    <option value="apple">Apple</option>
    <option value="orange">Apricot </option>
    <option value="melon">Peach</option>
    <option value="">Other..</option>
</select> <input type="text" name="fruit_txt" style="display: none;" />
<button type="submit">Submit</button>
</form>

JavaScript:

function DropDownChanged(oDDL) {
    var oTextbox = oDDL.form.elements["fruit_txt"];
    if (oTextbox) {
        oTextbox.style.display = (oDDL.value == "") ? "" : "none";
        if (oDDL.value == "")
            oTextbox.focus();
    }
}

function FormSubmit(oForm) {
    var oHidden = oForm.elements["fruit"];
    var oDDL = oForm.elements["fruit_ddl"];
    var oTextbox = oForm.elements["fruit_txt"];
    if (oHidden && oDDL && oTextbox)
        oHidden.value = (oDDL.value == "") ? oTextbox.value : oDDL.value;
}

And in the server side, read the value of "fruit" from the Request.

How to read data From *.CSV file using javascript?

Here's a JavaScript function that parses CSV data, accounting for commas found inside quotes.

// Parse a CSV row, accounting for commas inside quotes                   
function parse(row){
  var insideQuote = false,                                             
      entries = [],                                                    
      entry = [];
  row.split('').forEach(function (character) {                         
    if(character === '"') {
      insideQuote = !insideQuote;                                      
    } else {
      if(character == "," && !insideQuote) {                           
        entries.push(entry.join(''));                                  
        entry = [];                                                    
      } else {
        entry.push(character);                                         
      }                                                                
    }                                                                  
  });
  entries.push(entry.join(''));                                        
  return entries;                                                      
}

Example use of the function to parse a CSV file that looks like this:

"foo, the column",bar
2,3
"4, the value",5

into arrays:

// csv could contain the content read from a csv file
var csv = '"foo, the column",bar\n2,3\n"4, the value",5',

    // Split the input into lines
    lines = csv.split('\n'),

    // Extract column names from the first line
    columnNamesLine = lines[0],
    columnNames = parse(columnNamesLine),

    // Extract data from subsequent lines
    dataLines = lines.slice(1),
    data = dataLines.map(parse);

// Prints ["foo, the column","bar"]
console.log(JSON.stringify(columnNames));

// Prints [["2","3"],["4, the value","5"]]
console.log(JSON.stringify(data));

Here's how you can transform the data into objects, like D3's csv parser (which is a solid third party solution):

var dataObjects = data.map(function (arr) {
  var dataObject = {};
  columnNames.forEach(function(columnName, i){
    dataObject[columnName] = arr[i];
  });
  return dataObject;
});

// Prints [{"foo":"2","bar":"3"},{"foo":"4","bar":"5"}]
console.log(JSON.stringify(dataObjects));

Here's a working fiddle of this code.

Enjoy! --Curran

json_encode(): Invalid UTF-8 sequence in argument

Using this code might help. It solved my problem!

mb_convert_encoding($post["post"],'UTF-8','UTF-8');

or like that

mb_convert_encoding($string,'UTF-8','UTF-8');

check if a key exists in a bucket in s3 using boto3

Check out

bucket.get_key(
    key_name, 
    headers=None, 
    version_id=None, 
    response_headers=None, 
    validate=True
)

Check to see if a particular key exists within the bucket. This method uses a HEAD request to check for the existence of the key. Returns: An instance of a Key object or None

from Boto S3 Docs

You can just call bucket.get_key(keyname) and check if the returned object is None.

Counting duplicates in Excel

This can be done using pivot tables. See this youtube video for a walkthrough: Quickly Count Duplicates in Excel List With Pivot Table.

To count the number of times each item is duplicated in an Excel list, you can use a pivot table, instead of manually creating a list with formulas.

Converting Long to Date in Java returns 1970

Try this with adjusting the date format.

long longtime = 1212580300;
SimpleDateFormat dateFormat = new SimpleDateFormat("MMddyyHHmm");
Date date = (Date) dateFormat.parseObject(longtime + "");
System.out.println(date);

Note: Check for 24 hours or 12 hours cycle.

How to run a cronjob every X minutes?

In a crontab file, the fields are:

  • minute of the hour.
  • hour of the day.
  • day of the month.
  • month of the year.
  • day of the week.

So:

10 * * * * blah

means execute blah at 10 minutes past every hour.

If you want every five minutes, use either:

*/5 * * * * blah

meaning every minute but only every fifth one, or:

0,5,10,15,20,25,30,35,40,45,50,55 * * * * blah

for older cron executables that don't understand the */x notation.

If it still seems to be not working after that, change the command to something like:

date >>/tmp/debug_cron_pax.txt

and monitor that file to ensure something's being written every five minutes. If so, there's something wrong with your PHP scripts. If not, there's something wrong with your cron daemon.

How to include PHP files that require an absolute path?

@Flubba, does this allow me to have folders inside my include directory? flat include directories give me nightmares. as the whole objects directory should be in the inc directory.

Oh yes, absolutely. So for example, we use a single layer of subfolders, generally:

require_once('library/string.class.php')

You need to be careful with relying on the include path too much in really high traffic sites, because php has to hunt through the current directory and then all the directories on the include path in order to see if your file is there and this can slow things up if you're getting hammered.

So for example if you're doing MVC, you'd put the path to your application directoy in the include path and then specify refer to things in the form

'model/user.class'
'controllers/front.php'

or whatever.

But generally speaking, it just lets you work with really short paths in your PHP that will work from anywhere and it's a lot easier to read than all that realpath document root malarkey.

The benefit of those script-based alternatives others have suggested is they work anywhere, even on shared boxes; setting the include path requires a little more thought and effort but as I mentioned lets you start using __autoload which just the coolest.

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

You can check for text in your page source as follow:

Assert.IsTrue(driver.PageSource.Contains("Your Text Here"))

Difference between JE/JNE and JZ/JNZ

From the Intel's manual - Instruction Set Reference, the JE and JZ have the same opcode (74 for rel8 / 0F 84 for rel 16/32) also JNE and JNZ (75 for rel8 / 0F 85 for rel 16/32) share opcodes.

JE and JZ they both check for the ZF (or zero flag), although the manual differs slightly in the descriptions of the first JE rel8 and JZ rel8 ZF usage, but basically they are the same.

Here is an extract from the manual's pages 464, 465 and 467.

 Op Code    | mnemonic  | Description
 -----------|-----------|-----------------------------------------------  
 74 cb      | JE rel8   | Jump short if equal (ZF=1).
 74 cb      | JZ rel8   | Jump short if zero (ZF ? 1).

 0F 84 cw   | JE rel16  | Jump near if equal (ZF=1). Not supported in 64-bit mode.
 0F 84 cw   | JZ rel16  | Jump near if 0 (ZF=1). Not supported in 64-bit mode.

 0F 84 cd   | JE rel32  | Jump near if equal (ZF=1).
 0F 84 cd   | JZ rel32  | Jump near if 0 (ZF=1).

 75 cb      | JNE rel8  | Jump short if not equal (ZF=0).
 75 cb      | JNZ rel8  | Jump short if not zero (ZF=0).

 0F 85 cd   | JNE rel32 | Jump near if not equal (ZF=0).
 0F 85 cd   | JNZ rel32 | Jump near if not zero (ZF=0).

Simple Popup by using Angular JS

Built a modal popup example using syarul's jsFiddle link. Here is the updated fiddle.

Created an angular directive called modal and used in html. Explanation:-

HTML

<div ng-controller="MainCtrl" class="container">
  <button ng-click="toggleModal('Success')" class="btn btn-default">Success</button>
  <button ng-click="toggleModal('Remove')" class="btn btn-default">Remove</button>
  <button ng-click="toggleModal('Deny')" class="btn btn-default">Deny</button>
  <button ng-click="toggleModal('Cancel')" class="btn btn-default">Cancel</button>
  <modal visible="showModal">
      Any additional data / buttons
  </modal>
</div>

On button click toggleModal() function is called with the button message as parameter. This function toggles the visibility of popup. Any tags that you put inside will show up in the popup as content since ng-transclude is placed on modal-body in the directive template.

JS

var mymodal = angular.module('mymodal', []);

mymodal.controller('MainCtrl', function ($scope) {
    $scope.showModal = false;
    $scope.buttonClicked = "";
    $scope.toggleModal = function(btnClicked){
        $scope.buttonClicked = btnClicked;
        $scope.showModal = !$scope.showModal;
    };
  });

mymodal.directive('modal', function () {
    return {
      template: '<div class="modal fade">' + 
          '<div class="modal-dialog">' + 
            '<div class="modal-content">' + 
              '<div class="modal-header">' + 
                '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' + 
                '<h4 class="modal-title">{{ buttonClicked }} clicked!!</h4>' + 
              '</div>' + 
              '<div class="modal-body" ng-transclude></div>' + 
            '</div>' + 
          '</div>' + 
        '</div>',
      restrict: 'E',
      transclude: true,
      replace:true,
      scope:true,
      link: function postLink(scope, element, attrs) {
        scope.title = attrs.title;

        scope.$watch(attrs.visible, function(value){
          if(value == true)
            $(element).modal('show');
          else
            $(element).modal('hide');
        });

        $(element).on('shown.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = true;
          });
        });

        $(element).on('hidden.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = false;
          });
        });
      }
    };
  });

UPDATE

<!doctype html>
<html ng-app="mymodal">


<body>

<div ng-controller="MainCtrl" class="container">
  <button ng-click="toggleModal('Success')" class="btn btn-default">Success</button>
  <button ng-click="toggleModal('Remove')" class="btn btn-default">Remove</button>
  <button ng-click="toggleModal('Deny')" class="btn btn-default">Deny</button>
  <button ng-click="toggleModal('Cancel')" class="btn btn-default">Cancel</button>
  <modal visible="showModal">
      Any additional data / buttons
  </modal>
</div>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
        <!-- Scripts -->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>

    <!-- App -->
    <script>
        var mymodal = angular.module('mymodal', []);

mymodal.controller('MainCtrl', function ($scope) {
    $scope.showModal = false;
    $scope.buttonClicked = "";
    $scope.toggleModal = function(btnClicked){
        $scope.buttonClicked = btnClicked;
        $scope.showModal = !$scope.showModal;
    };
  });

mymodal.directive('modal', function () {
    return {
      template: '<div class="modal fade">' + 
          '<div class="modal-dialog">' + 
            '<div class="modal-content">' + 
              '<div class="modal-header">' + 
                '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' + 
                '<h4 class="modal-title">{{ buttonClicked }} clicked!!</h4>' + 
              '</div>' + 
              '<div class="modal-body" ng-transclude></div>' + 
            '</div>' + 
          '</div>' + 
        '</div>',
      restrict: 'E',
      transclude: true,
      replace:true,
      scope:true,
      link: function postLink(scope, element, attrs) {
          scope.$watch(attrs.visible, function(value){
          if(value == true)
            $(element).modal('show');
          else
            $(element).modal('hide');
        });

        $(element).on('shown.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = true;
          });
        });

        $(element).on('hidden.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = false;
          });
        });
      }
    };
  });

    </script>
</body>
</html>

UPDATE 2 restrict : 'E' : directive to be used as an HTML tag (element). Example in our case is

<modal>

Other values are 'A' for attribute

<div modal>

'C' for class (not preferable in our case because modal is already a class in bootstrap.css)

<div class="modal">

Converting URL to String and back again

Swift 5.

To convert a String to a URL:

let stringToURL = URL(string: "your-string")

To convert a URL to a String:

let urlToString = stringToURL?.absoluteString

Reading a JSP variable from JavaScript

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> 

    <title>JSP Page</title>
    <script>
       $(document).ready(function(){
          <% String name = "phuongmychi.github.io" ;%> // jsp vari
         var name = "<%=name %>" // call var to js
         $("#id").html(name); //output to html

       });
    </script>
</head>
<body>
    <h1 id='id'>!</h1>
</body>

Git pull command from different user

Your question is a little unclear, but if what you're doing is trying to get your friend's latest changes, then typically what your friend needs to do is to push those changes up to a remote repo (like one hosted on GitHub), and then you fetch or pull those changes from the remote:

  1. Your friend pushes his changes to GitHub:

    git push origin <branch>
    
  2. Clone the remote repository if you haven't already:

    git clone https://[email protected]/abc/theproject.git
    
  3. Fetch or pull your friend's changes (unnecessary if you just cloned in step #2 above):

    git fetch origin
    git merge origin/<branch>
    

    Note that git pull is the same as doing the two steps above:

    git pull origin <branch>
    

See Also

fatal: bad default revision 'HEAD'

This happens to me when the branch I'm working in gets deleted from the repository, but the workspace I'm in is not updated. (We have a tool that lets you create multiple git "workspaces" from the same repository using simlinks.)

If git branch does not mark any branch as current, try doing

git reset --hard <<some branch>>

I tried a number of approaches until I worked this one out.

crudrepository findBy method signature with multiple in operators?

The following signature will do:

List<Email> findByEmailIdInAndPincodeIn(List<String> emails, List<String> pinCodes);

Spring Data JPA supports a large number of keywords to build a query. IN and AND are among them.

Using mysql concat() in WHERE clause?

SELECT *,concat_ws(' ',first_name,last_name) AS whole_name FROM users HAVING whole_name LIKE '%$search_term%'

...is probably what you want.

error CS0234: The type or namespace name 'Script' does not exist in the namespace 'System.Web'

Add System.Web.Extensions as a reference to your project

enter image description here

For Ref.

How to get current relative directory of your Makefile?

Example for your reference, as below:

The folder structure might be as:

enter image description here

Where there are two Makefiles, each as below;

sample/Makefile
test/Makefile

Now, let us see the content of the Makefiles.

sample/Makefile

export ROOT_DIR=${PWD}

all:
    echo ${ROOT_DIR}
    $(MAKE) -C test

test/Makefile

all:
    echo ${ROOT_DIR}
    echo "make test ends here !"

Now, execute the sample/Makefile, as;

cd sample
make

OUTPUT:

echo /home/symphony/sample
/home/symphony/sample
make -C test
make[1]: Entering directory `/home/symphony/sample/test'
echo /home/symphony/sample
/home/symphony/sample
echo "make test ends here !"
make test ends here !
make[1]: Leaving directory `/home/symphony/sample/test'

Explanation, would be that the parent/home directory can be stored in the environment-flag, and can be exported, so that it can be used in all the sub-directory makefiles.

Python, how to read bytes from file and save it?

In my examples I use the 'b' flag ('wb', 'rb') when opening the files because you said you wanted to read bytes. The 'b' flag tells Python not to interpret end-of-line characters which can differ between operating systems. If you are reading text, then omit the 'b' and use 'w' and 'r' respectively.

This reads the entire file in one chunk using the "simplest" Python code. The problem with this approach is that you could run out memory when reading a large file:

ifile = open(input_filename,'rb')
ofile = open(output_filename, 'wb')
ofile.write(ifile.read())
ofile.close()
ifile.close()

This example is refined to read 1MB chunks to ensure it works for files of any size without running out of memory:

ifile = open(input_filename,'rb')
ofile = open(output_filename, 'wb')
data = ifile.read(1024*1024)
while data:
    ofile.write(data)
    data = ifile.read(1024*1024)
ofile.close()
ifile.close()

This example is the same as above but leverages using with to create a context. The advantage of this approach is that the file is automatically closed when exiting the context:

with open(input_filename,'rb') as ifile:
    with open(output_filename, 'wb') as ofile:
        data = ifile.read(1024*1024)
        while data:
            ofile.write(data)
            data = ifile.read(1024*1024)

See the following:

NSOperation vs Grand Central Dispatch

In line with my answer to a related question, I'm going to disagree with BJ and suggest you first look at GCD over NSOperation / NSOperationQueue, unless the latter provides something you need that GCD doesn't.

Before GCD, I used a lot of NSOperations / NSOperationQueues within my applications for managing concurrency. However, since I started using GCD on a regular basis, I've almost entirely replaced NSOperations and NSOperationQueues with blocks and dispatch queues. This has come from how I've used both technologies in practice, and from the profiling I've performed on them.

First, there is a nontrivial amount of overhead when using NSOperations and NSOperationQueues. These are Cocoa objects, and they need to be allocated and deallocated. In an iOS application that I wrote which renders a 3-D scene at 60 FPS, I was using NSOperations to encapsulate each rendered frame. When I profiled this, the creation and teardown of these NSOperations was accounting for a significant portion of the CPU cycles in the running application, and was slowing things down. I replaced these with simple blocks and a GCD serial queue, and that overhead disappeared, leading to noticeably better rendering performance. This wasn't the only place where I noticed overhead from using NSOperations, and I've seen this on both Mac and iOS.

Second, there's an elegance to block-based dispatch code that is hard to match when using NSOperations. It's so incredibly convenient to wrap a few lines of code in a block and dispatch it to be performed on a serial or concurrent queue, where creating a custom NSOperation or NSInvocationOperation to do this requires a lot more supporting code. I know that you can use an NSBlockOperation, but you might as well be dispatching something to GCD then. Wrapping this code in blocks inline with related processing in your application leads in my opinion to better code organization than having separate methods or custom NSOperations which encapsulate these tasks.

NSOperations and NSOperationQueues still have very good uses. GCD has no real concept of dependencies, where NSOperationQueues can set up pretty complex dependency graphs. I use NSOperationQueues for this in a handful of cases.

Overall, while I usually advocate for using the highest level of abstraction that accomplishes the task, this is one case where I argue for the lower-level API of GCD. Among the iOS and Mac developers I've talked with about this, the vast majority choose to use GCD over NSOperations unless they are targeting OS versions without support for it (those before iOS 4.0 and Snow Leopard).

Python dictionary : TypeError: unhashable type: 'list'

It works fine : http://codepad.org/5KgO0b1G, your aSourceDictionary variable may have other datatype than dict

aSourceDictionary = { 'abc' : [1,2,3] , 'ccd' : [4,5] }
aTargetDictionary = {}
for aKey in aSourceDictionary:
        aTargetDictionary[aKey] = []
        aTargetDictionary[aKey].extend(aSourceDictionary[aKey])
print aTargetDictionary

Python Variable Declaration

For scoping purpose, I use:

custom_object = None

Mvn install or Mvn package

mvn install is the option that is most often used.
mvn package is seldom used, only if you're debugging some issue with the maven build process.

See: http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html

Note that mvn package will only create a jar file.
mvn install will do that and install the jar (and class etc.) files in the proper places if other code depends on those jars.

I usually do a mvn clean install; this deletes the target directory and recreates all jars in that location.
The clean helps with unneeded or removed stuff that can sometimes get in the way.
Rather then debug (some of the time) just start fresh all of the time.

Is there a Public FTP server to test upload and download?

Currently, the link dlptest is working fine.

The files will only be stored for 30 minutes before being deleted.

Insert picture/table in R Markdown

In March I made a deck presentation in slidify, Rmarkdown with impress.js which is a cool 3D framework. My index.Rmdheader looks like

---
title       : French TER (regional train) monthly regularity
subtitle    : since January 2013
author      : brigasnuncamais
job         : Business Intelligence / Data Scientist consultant
framework   : impressjs     # {io2012, html5slides, shower, dzslides, ...}
highlighter : highlight.js  # {highlight.js, prettify, highlight}
hitheme     : tomorrow      # 
widgets     : []            # {mathjax, quiz, bootstrap}
mode        : selfcontained # {standalone, draft}
knit        : slidify::knit2slides

subdirs are:

/assets /css    /impress-demo.css
        /fig    /unnamed-chunk-1-1.png (generated by included R code)
        /img    /SS850452.png (my image used as background)
        /js     /impress.js
        /layouts/custbg.html # content:--- layout: slide --- {{{ slide.html }}}
        /libraries  /frameworks /impressjs
                                /io2012
                    /highlighters   /highlight.js
                                    /impress.js
index.Rmd

A slide with image in background code snippet would be in my .Rmd:

<div id="bg">
  <img src="assets/img/SS850452.png" alt="">
</div>  

Some issues appeared since I last worked on it (photos are no more in background, text it too large on my R plot) but it works fine on my local. Troubles come when I run it on RPubs.

What is the size of a pointer?

Function Pointers can have very different sizes, from 4 to 20 Bytes on an X86 machine, depending on the compiler. So the answer is NO - sizes can vary.

Another example: take an 8051 program, it has three memory ranges and thus has three different pointer sizes, from 8 bit, 16bit, 24bit, depending on where the target is located, even though the target's size is always the same (e.g. char).

Python - Check If Word Is In A String

if 'seek' in 'those who seek shall find':
    print('Success!')

but keep in mind that this matches a sequence of characters, not necessarily a whole word - for example, 'word' in 'swordsmith' is True. If you only want to match whole words, you ought to use regular expressions:

import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> <match object>
findWholeWord('word')('swordsmith')                   # -> None

Print the data in ResultSet along with column names

For those who wanted more better version of the resultset printing as util class This was really helpful for printing resultset and does many things from a single util... thanks to Hami Torun!

In this class printResultSet uses ResultSetMetaData in a generic way have a look at it..


import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

public final class DBTablePrinter {

    /**
     * Column type category for CHAR, VARCHAR
     * and similar text columns.
     */
    public static final int CATEGORY_STRING = 1;
    /**
     * Column type category for TINYINT, SMALLINT,
     * INT and BIGINT columns.
     */
    public static final int CATEGORY_INTEGER = 2;
    /**
     * Column type category for REAL, DOUBLE,
     * and DECIMAL columns.
     */
    public static final int CATEGORY_DOUBLE = 3;
    /**
     * Column type category for date and time related columns like
     * DATE, TIME, TIMESTAMP etc.
     */
    public static final int CATEGORY_DATETIME = 4;
    /**
     * Column type category for BOOLEAN columns.
     */
    public static final int CATEGORY_BOOLEAN = 5;
    /**
     * Column type category for types for which the type name
     * will be printed instead of the content, like BLOB,
     * BINARY, ARRAY etc.
     */
    public static final int CATEGORY_OTHER = 0;
    /**
     * Default maximum number of rows to query and print.
     */
    private static final int DEFAULT_MAX_ROWS = 10;
    /**
     * Default maximum width for text columns
     * (like a VARCHAR) column.
     */
    private static final int DEFAULT_MAX_TEXT_COL_WIDTH = 150;

    /**
     * Overloaded method that prints rows from table tableName
     * to standard out using the given database connection
     * conn. Total number of rows will be limited to
     * {@link #DEFAULT_MAX_ROWS} and
     * {@link #DEFAULT_MAX_TEXT_COL_WIDTH} will be used to limit
     * the width of text columns (like a VARCHAR column).
     *
     * @param conn      Database connection object (java.sql.Connection)
     * @param tableName Name of the database table
     */
    public static void printTable(Connection conn, String tableName) {
        printTable(conn, tableName, DEFAULT_MAX_ROWS, DEFAULT_MAX_TEXT_COL_WIDTH);
    }

    /**
     * Overloaded method that prints rows from table tableName
     * to standard out using the given database connection
     * conn. Total number of rows will be limited to
     * maxRows and
     * {@link #DEFAULT_MAX_TEXT_COL_WIDTH} will be used to limit
     * the width of text columns (like a VARCHAR column).
     *
     * @param conn      Database connection object (java.sql.Connection)
     * @param tableName Name of the database table
     * @param maxRows   Number of max. rows to query and print
     */
    public static void printTable(Connection conn, String tableName, int maxRows) {
        printTable(conn, tableName, maxRows, DEFAULT_MAX_TEXT_COL_WIDTH);
    }

    /**
     * Overloaded method that prints rows from table tableName
     * to standard out using the given database connection
     * conn. Total number of rows will be limited to
     * maxRows and
     * maxStringColWidth will be used to limit
     * the width of text columns (like a VARCHAR column).
     *
     * @param conn              Database connection object (java.sql.Connection)
     * @param tableName         Name of the database table
     * @param maxRows           Number of max. rows to query and print
     * @param maxStringColWidth Max. width of text columns
     */
    public static void printTable(Connection conn, String tableName, int maxRows, int maxStringColWidth) {
        if (conn == null) {
            System.err.println("DBTablePrinter Error: No connection to database (Connection is null)!");
            return;
        }
        if (tableName == null) {
            System.err.println("DBTablePrinter Error: No table name (tableName is null)!");
            return;
        }
        if (tableName.length() == 0) {
            System.err.println("DBTablePrinter Error: Empty table name!");
            return;
        }
        if (maxRows 
     * ResultSet to standard out using {@link #DEFAULT_MAX_TEXT_COL_WIDTH}
     * to limit the width of text columns.
     *
     * @param rs The ResultSet to print
     */
    public static void printResultSet(ResultSet rs) {
        printResultSet(rs, DEFAULT_MAX_TEXT_COL_WIDTH);
    }

    /**
     * Overloaded method to print rows of a 
     * ResultSet to standard out using maxStringColWidth
     * to limit the width of text columns.
     *
     * @param rs                The ResultSet to print
     * @param maxStringColWidth Max. width of text columns
     */
    public static void printResultSet(ResultSet rs, int maxStringColWidth) {
        try {
            if (rs == null) {
                System.err.println("DBTablePrinter Error: Result set is null!");
                return;
            }
            if (rs.isClosed()) {
                System.err.println("DBTablePrinter Error: Result Set is closed!");
                return;
            }
            if (maxStringColWidth  columns = new ArrayList(columnCount);

            // List of table names. Can be more than one if it is a joined
            // table query
            List tableNames = new ArrayList(columnCount);

            // Get the columns and their meta data.
            // NOTE: columnIndex for rsmd.getXXX methods STARTS AT 1 NOT 0
            for (int i = 1; i  maxStringColWidth) {
                                value = value.substring(0, maxStringColWidth - 3) + "...";
                            }
                            break;
                    }

                    // Adjust the column width
                    c.setWidth(value.length() > c.getWidth() ? value.length() : c.getWidth());
                    c.addValue(value);
                } // END of for loop columnCount
                rowCount++;

            } // END of while (rs.next)

            /*
            At this point we have gone through meta data, get the
            columns and created all Column objects, iterated over the
            ResultSet rows, populated the column values and adjusted
            the column widths.
            We cannot start printing just yet because we have to prepare
            a row separator String.
             */

            // For the fun of it, I will use StringBuilder
            StringBuilder strToPrint = new StringBuilder();
            StringBuilder rowSeparator = new StringBuilder();

            /*
            Prepare column labels to print as well as the row separator.
            It should look something like this:
            +--------+------------+------------+-----------+  (row separator)
            | EMP_NO | BIRTH_DATE | FIRST_NAME | LAST_NAME |  (labels row)
            +--------+------------+------------+-----------+  (row separator)
             */

            // Iterate over columns
            for (Column c : columns) {
                int width = c.getWidth();

                // Center the column label
                String toPrint;
                String name = c.getLabel();
                int diff = width - name.length();

                if ((diff % 2) == 1) {
                    // diff is not divisible by 2, add 1 to width (and diff)
                    // so that we can have equal padding to the left and right
                    // of the column label.
                    width++;
                    diff++;
                    c.setWidth(width);
                }

                int paddingSize = diff / 2; // InteliJ says casting to int is redundant.

                // Cool String repeater code thanks to user102008 at stackoverflow.com

                String padding = new String(new char[paddingSize]).replace("\0", " ");

                toPrint = "| " + padding + name + padding + " ";
                // END centering the column label

                strToPrint.append(toPrint);

                rowSeparator.append("+");
                rowSeparator.append(new String(new char[width + 2]).replace("\0", "-"));
            }

            String lineSeparator = System.getProperty("line.separator");

            // Is this really necessary ??
            lineSeparator = lineSeparator == null ? "\n" : lineSeparator;

            rowSeparator.append("+").append(lineSeparator);

            strToPrint.append("|").append(lineSeparator);
            strToPrint.insert(0, rowSeparator);
            strToPrint.append(rowSeparator);

            StringJoiner sj = new StringJoiner(", ");
            for (String name : tableNames) {
                sj.add(name);
            }

            String info = "Printing " + rowCount;
            info += rowCount > 1 ? " rows from " : " row from ";
            info += tableNames.size() > 1 ? "tables " : "table ";
            info += sj.toString();

            System.out.println(info);

            // Print out the formatted column labels
            System.out.print(strToPrint.toString());

            String format;

            // Print out the rows
            for (int i = 0; i 
     * Integers should not be truncated so column widths should
     * be adjusted without a column width limit. Text columns should be
     * left justified and can be truncated to a max. column width etc...

*

* See also: * java.sql.Types * * @param type Generic SQL type * @return The category this type belongs to */ private static int whichCategory(int type) { switch (type) { case Types.BIGINT: case Types.TINYINT: case Types.SMALLINT: case Types.INTEGER: return CATEGORY_INTEGER; case Types.REAL: case Types.DOUBLE: case Types.DECIMAL: return CATEGORY_DOUBLE; case Types.DATE: case Types.TIME: case Types.TIME_WITH_TIMEZONE: case Types.TIMESTAMP: case Types.TIMESTAMP_WITH_TIMEZONE: return CATEGORY_DATETIME; case Types.BOOLEAN: return CATEGORY_BOOLEAN; case Types.VARCHAR: case Types.NVARCHAR: case Types.LONGVARCHAR: case Types.LONGNVARCHAR: case Types.CHAR: case Types.NCHAR: return CATEGORY_STRING; default: return CATEGORY_OTHER; } } /** * Represents a database table column. */ private static class Column { /** * Column label. */ private String label; /** * Generic SQL type of the column as defined in * * java.sql.Types * . */ private int type; /** * Generic SQL type name of the column as defined in * * java.sql.Types * . */ private String typeName; /** * Width of the column that will be adjusted according to column label * and values to be printed. */ private int width = 0; /** * Column values from each row of a ResultSet. */ private List values = new ArrayList(); /** * Flag for text justification using String.format. * Empty string ("") to justify right, * dash (-) to justify left. * * @see #justifyLeft() */ private String justifyFlag = ""; /** * Column type category. The columns will be categorised according * to their column types and specific needs to print them correctly. */ private int typeCategory = 0; /** * Constructs a new Column with a column label, * generic SQL type and type name (as defined in * * java.sql.Types * ) * * @param label Column label or name * @param type Generic SQL type * @param typeName Generic SQL type name */ public Column(String label, int type, String typeName) { this.label = label; this.type = type; this.typeName = typeName; } /** * Returns the column label * * @return Column label */ public String getLabel() { return label; } /** * Returns the generic SQL type of the column * * @return Generic SQL type */ public int getType() { return type; } /** * Returns the generic SQL type name of the column * * @return Generic SQL type name */ public String getTypeName() { return typeName; } /** * Returns the width of the column * * @return Column width */ public int getWidth() { return width; } /** * Sets the width of the column to width * * @param width Width of the column */ public void setWidth(int width) { this.width = width; } /** * Adds a String representation (value) * of a value to this column object's {@link #values} list. * These values will come from each row of a * * ResultSet * of a database query. * * @param value The column value to add to {@link #values} */ public void addValue(String value) { values.add(value); } /** * Returns the column value at row index i. * Note that the index starts at 0 so that getValue(0) * will get the value for this column from the first row * of a * ResultSet. * * @param i The index of the column value to get * @return The String representation of the value */ public String getValue(int i) { return values.get(i); } /** * Returns the value of the {@link #justifyFlag}. The column * values will be printed using String.format and * this flag will be used to right or left justify the text. * * @return The {@link #justifyFlag} of this column * @see #justifyLeft() */ public String getJustifyFlag() { return justifyFlag; } /** * Sets {@link #justifyFlag} to "-" so that * the column value will be left justified when printed with * String.format. Typically numbers will be right * justified and text will be left justified. */ public void justifyLeft() { this.justifyFlag = "-"; } /** * Returns the generic SQL type category of the column * * @return The {@link #typeCategory} of the column */ public int getTypeCategory() { return typeCategory; } /** * Sets the {@link #typeCategory} of the column * * @param typeCategory The type category */ public void setTypeCategory(int typeCategory) { this.typeCategory = typeCategory; } } }

This is the scala version of doing this... which will print column names and data as well in a generic way...

def printQuery(res: ResultSet): Unit = {
    val rsmd = res.getMetaData
    val columnCount = rsmd.getColumnCount
    var rowCnt = 0
    val s = StringBuilder.newBuilder
    while (res.next()) {

      s.clear()
      if (rowCnt == 0) {
        s.append("| ")
        for (i <- 1 to columnCount) {
          val name = rsmd.getColumnName(i)
          s.append(name)
          s.append("| ")
        }
        s.append("\n")
      }
      rowCnt += 1
      s.append("| ")
      for (i <- 1 to columnCount) {
        if (i > 1)
          s.append(" | ")
        s.append(res.getString(i))
      }
      s.append(" |")
      System.out.println(s)
    }
    System.out.println(s"TOTAL: $rowCnt rows")
  }

Stash just a single file

I think stash -p is probably the choice you want, but just in case you run into other even more tricky things in the future, remember that:

Stash is really just a very simple alternative to the only slightly more complex branch sets. Stash is very useful for moving things around quickly, but you can accomplish more complex things with branches without that much more headache and work.

# git checkout -b tmpbranch
# git add the_file
# git commit -m "stashing the_file"
# git checkout master

go about and do what you want, and then later simply rebase and/or merge the tmpbranch. It really isn't that much extra work when you need to do more careful tracking than stash will allow.

How to check if an integer is in a given range?

If you're looking for something more original than

if (i > 0 && i < 100)

you can try this

import static java.lang.Integer.compare;
...
if(compare(i, 0) > compare(i, 100))

How to redirect to another page using PHP

On click BUTTON action

   if(isset($_POST['save_btn']))
    {
        //write some of your code here, if necessary
        echo'<script> window.location="B.php"; </script> ';
     }

Jupyter Notebook not saving: '_xsrf' argument missing from post

This is the easiest way.

I did not need to open a new notebook. Instead, I reopened the tree, and reconnected the kernel. At some point I also restarted the kernel. – user650654 Oct 9 '19 at 0:17

Is there a way to check if a file is in use?

Just use the exception as intended. Accept that the file is in use and try again, repeatedly until your action is completed. This is also the most efficient because you do not waste any cycles checking the state before acting.

Use the function below, for example

TimeoutFileAction(() => { System.IO.File.etc...; return null; } );

Reusable method that times out after 2 seconds

private T TimeoutFileAction<T>(Func<T> func)
{
    var started = DateTime.UtcNow;
    while ((DateTime.UtcNow - started).TotalMilliseconds < 2000)
    {
        try
        {
            return func();                    
        }
        catch (System.IO.IOException exception)
        {
            //ignore, or log somewhere if you want to
        }
    }
    return default(T);
}

Angular 2 change event - model changes

If this helps you,

<input type="checkbox"  (ngModelChange)="mychange($event)" [ngModel]="mymodel">

mychange(val)
{
   console.log(val); // updated value
}

Rails 3 execute custom sql query without a model

I'd recommend using ActiveRecord::Base.connection.exec_query instead of ActiveRecord::Base.connection.execute which returns a ActiveRecord::Result (available in rails 3.1+) which is a bit easier to work with.

Then you can access it in various the result in various ways like .rows, .each, or .to_hash

From the docs:

result = ActiveRecord::Base.connection.exec_query('SELECT id, title, body FROM posts')
result # => #<ActiveRecord::Result:0xdeadbeef>


# Get the column names of the result:
result.columns
# => ["id", "title", "body"]

# Get the record values of the result:
result.rows
# => [[1, "title_1", "body_1"],
      [2, "title_2", "body_2"],
      ...
     ]

# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
      {"id" => 2, "title" => "title_2", "body" => "body_2"},
      ...
     ]

# ActiveRecord::Result also includes Enumerable.
result.each do |row|
  puts row['title'] + " " + row['body']
end

note: copied my answer from here

A child container failed during start java.util.concurrent.ExecutionException

I try with http servlet and I find this issue when I write duplicated @WebServlet ,I encountered with this issue.After I remove or change @WebServlet value it is working.

1.Class

@WebServlet("/display")
public class MyFirst extends HttpServlet {

2.Class

@WebServlet("/display")
public class MySecond extends HttpServlet {

"Warning: iPhone apps should include an armv6 architecture" even with build config set

Using Xcode 4.2 on Snow Leopard, I used the following settings to build an app that worked on both armv6 (Iphone 3G and lower) AND armv7 (everything newer than 3G including 3GS).

architectures: armv6 and armv7 (removed $(ARCHS_STANDARD_32_BIT))
build active architecture only: no
required device capabilities: armv6

do not put armv7 in required device capabilities if you want the app to run on 3G and lower as well.

How to delete node from XML file using C#

DocumentElement is the root node of the document so childNodes[1] doesn't exist in that document. childNodes[0] would be the <Settings> node

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

If it's a nested Type, you might be forgetting to transform a . to a +

Regardless, typeof( T).FullName will tell you what you should be saying

EDIT: BTW the usings (as I'm sure you know) are only directives to the compiler at compile time and cannot thus have any impact on the API call's success. (If you had project or assembly references, that could potentially have had influence - hence the information isnt useless, it just takes some filtering...)

How do I rename a Git repository?

If you are using GitLab or GitHub, then you can modify those files graphically.

Using GitLab

Go to your project Settings. There you can modify the name of the project and most importantly you can rename your repository (that's when you start getting in the danger section).

Once this is done, local clients configurations must be updated using

git remote set-url origin sshuser@gitlab-url:GROUP/new-project-name.git

Stop embedded youtube iframe?

How we Pause/stop YouTube iframe to when we use embed videos in modalpopup

 $('#close_one').click(function (e) {
         
         
         let link = document.querySelector('.divclass');// get iframe class 
         let link = document.querySelector('#divid');// get iframe id
         let video_src = link.getAttribute('src');

         $('.youtube-video').children('iframe').attr('src', ''); // set iframe parent div value null 
         $('.youtube-video').children('iframe').attr('src', video_src);// set iframe src again it works perfect

     });

Python Pandas - Missing required dependencies ['numpy'] 1

I had this problem with last version of numpy 1.16.x

Problem resolved with

python3 -m pip uninstall numpy

python3 -m pip install numpy==1.14.0

CSS text-overflow in a table cell?

Why does this happen?

It seems this section on w3.org suggests that text-overflow applies only to block elements:

11.1.  Overflow Ellipsis: the ‘text-overflow’ property

text-overflow      clip | ellipsis | <string>  
Initial:           clip   
APPLIES TO:        BLOCK CONTAINERS               <<<<
Inherited:         no  
Percentages:       N/A  
Media:             visual  
Computed value:    as specified  

The MDN says the same.

This jsfiddle has your code (with a few debug modifications), which works fine if it's applied to a div instead of a td. It also has the only workaround I could quickly think of, by wrapping the contents of the td in a containing div block. However, that looks like "ugly" markup to me, so I'm hoping someone else has a better solution. The code to test this looks like this:

_x000D_
_x000D_
td, div {_x000D_
  overflow: hidden;_x000D_
  text-overflow: ellipsis;_x000D_
  white-space: nowrap;_x000D_
  border: 1px solid red;_x000D_
  width: 80px;_x000D_
}
_x000D_
Works, but no tables anymore:_x000D_
<div>Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah.</div>_x000D_
_x000D_
Works, but non-semantic markup required:_x000D_
<table><tr><td><div>Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah.</div></td></tr></table>
_x000D_
_x000D_
_x000D_

ConfigurationManager.AppSettings - How to modify and save?

Remember that ConfigurationManager uses only one app.config - one that is in startup project.

If you put some app.config to a solution A and make a reference to it from another solution B then if you run B, app.config from A will be ignored.

So for example unit test project should have their own app.config.

Excel formula to get cell color

As commented, just in case the link I posted there broke, try this:

Add a Name(any valid name) in Excel's Name Manager under Formula tab in the Ribbon.
Then assign a formula using GET.CELL function.

=GET.CELL(63,INDIRECT("rc",FALSE))

63 stands for backcolor.
Let's say we name it Background so in any cell with color type:

=Background

Result:
enter image description here

Notice that Cells A2, A3 and A4 returns 3, 4, and 5 respectively which equates to the cells background color index. HTH.
BTW, here's a link on Excel's Color Index

How to generate gcc debug symbol outside the build target?

You need to use objcopy to separate the debug information:

objcopy --only-keep-debug "${tostripfile}" "${debugdir}/${debugfile}"
strip --strip-debug --strip-unneeded "${tostripfile}"
objcopy --add-gnu-debuglink="${debugdir}/${debugfile}" "${tostripfile}"

I use the bash script below to separate the debug information into files with a .debug extension in a .debug directory. This way I can tar the libraries and executables in one tar file and the .debug directories in another. If I want to add the debug info later on I simply extract the debug tar file and voila I have symbolic debug information.

This is the bash script:

#!/bin/bash

scriptdir=`dirname ${0}`
scriptdir=`(cd ${scriptdir}; pwd)`
scriptname=`basename ${0}`

set -e

function errorexit()
{
  errorcode=${1}
  shift
  echo $@
  exit ${errorcode}
}

function usage()
{
  echo "USAGE ${scriptname} <tostrip>"
}

tostripdir=`dirname "$1"`
tostripfile=`basename "$1"`


if [ -z ${tostripfile} ] ; then
  usage
  errorexit 0 "tostrip must be specified"
fi

cd "${tostripdir}"

debugdir=.debug
debugfile="${tostripfile}.debug"

if [ ! -d "${debugdir}" ] ; then
  echo "creating dir ${tostripdir}/${debugdir}"
  mkdir -p "${debugdir}"
fi
echo "stripping ${tostripfile}, putting debug info into ${debugfile}"
objcopy --only-keep-debug "${tostripfile}" "${debugdir}/${debugfile}"
strip --strip-debug --strip-unneeded "${tostripfile}"
objcopy --add-gnu-debuglink="${debugdir}/${debugfile}" "${tostripfile}"
chmod -x "${debugdir}/${debugfile}"

jQuery: how to scroll to certain anchor/div on page load?

Have a look at this

Appending the #value into the address is default behaviour that browsers such as IE use to identify named anchor positions on the page, seeing this comes from Netscape.

You can intercept it and remove it, read this article.

PHP file_get_contents() returns "failed to open stream: HTTP request failed!"

<?php

$lurl=get_fcontent("http://ip2.cc/?api=cname&ip=84.228.229.81");
echo"cid:".$lurl[0]."<BR>";


function get_fcontent( $url,  $javascript_loop = 0, $timeout = 5 ) {
    $url = str_replace( "&amp;", "&", urldecode(trim($url)) );

    $cookie = tempnam ("/tmp", "CURLCOOKIE");
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
    curl_setopt( $ch, CURLOPT_URL, $url );
    curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie );
    curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
    curl_setopt( $ch, CURLOPT_ENCODING, "" );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );    # required for https urls
    curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
    curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
    curl_setopt( $ch, CURLOPT_MAXREDIRS, 10 );
    $content = curl_exec( $ch );
    $response = curl_getinfo( $ch );
    curl_close ( $ch );

    if ($response['http_code'] == 301 || $response['http_code'] == 302) {
        ini_set("user_agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1");

        if ( $headers = get_headers($response['url']) ) {
            foreach( $headers as $value ) {
                if ( substr( strtolower($value), 0, 9 ) == "location:" )
                    return get_url( trim( substr( $value, 9, strlen($value) ) ) );
            }
        }
    }

    if (    ( preg_match("/>[[:space:]]+window\.location\.replace\('(.*)'\)/i", $content, $value) || preg_match("/>[[:space:]]+window\.location\=\"(.*)\"/i", $content, $value) ) && $javascript_loop < 5) {
        return get_url( $value[1], $javascript_loop+1 );
    } else {
        return array( $content, $response );
    }
}


?>

How to resolve ORA-011033: ORACLE initialization or shutdown in progress

The issue can also be due to lack of hard drive space. The installation will succeed but on startup, oracle won't be able to create the required files and will fail with the same above error message.

Angular - Use pipes in services and components

Other answers don't work in angular 5?

I got an error because DatePipe is not a provider, so it cannot be injected. One solution is to put it as a provider in your app module but my preferred solution was to instantiate it.

Instantiate it where needed:

I looked at DatePipe's source code to see how it got the locale: https://github.com/angular/angular/blob/5.2.5/packages/common/src/pipes/date_pipe.ts#L15-L174

I wanted to use it within a pipe, so my example is within another pipe:

    import { Pipe, PipeTransform, Inject, LOCALE_ID } from '@angular/core';
    import { DatePipe } from '@angular/common';

    @Pipe({
        name: 'when',
    })
    export class WhenPipe implements PipeTransform {
        static today = new Date((new Date).toDateString().split(' ').slice(1).join(' '));
        datePipe: DatePipe;

        constructor(@Inject(LOCALE_ID) private locale: string) {
            this.datePipe = new DatePipe(locale);
        }
        transform(value: string | Date): string {
            if (typeof(value) === 'string')
                value = new Date(value);

            return this.datePipe.transform(value, value < WhenPipe.today ? 'MMM d': 'shortTime')
        }
    }

The key here is importing Inject, and LOCALE_ID from angular's core, and then injecting that so you can give it to the DatePipe to instantiate it properly.

Make DatePipe a provider

In your app module you could also add DatePipe to your providers array like this:

    import { DatePipe } from '@angular/common';

    @NgModule({
        providers: [
            DatePipe
        ]
    })

Now you can just have it injected in your constructor where needed (like in cexbrayat's answer).

Summary:

Either solution worked, I don't know which one angular would consider most "correct" but I chose to instantiate it manually since angular didn't provide datepipe as a provider itself.

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

I solved this problem removing DbproviderFactory in the section system.data of the file machine.config, there was some dirty data when I installed fbclient.dll.

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\machine.config C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\machine.config

  <system.data>
    <!-- <DbProviderFactories><add name="FirebirdClient Data Provider" invariant="FirebirdSql.Data.FirebirdClient" description=".NET Framework Data Provider for Firebird" type="FirebirdSql.Data.FirebirdClient.FirebirdClientFactory, FirebirdSql.Data.FirebirdClient, Version=4.10.0.0, Culture=neutral, PublicKeyToken=3750abcc3150b00c"/><add name="FirebirdClient Data Provider" invariant="FirebirdSql.Data.FirebirdClient" description=".NET Framework Data Provider for Firebird" type="FirebirdSql.Data.FirebirdClient.FirebirdClientFactory, FirebirdSql.Data.FirebirdClient, Version=6.4.0.0, Culture=neutral, PublicKeyToken=3750abcc3150b00c"/> -->
  </system.data>

How to break lines at a specific character in Notepad++?

Try this way. It got worked for me

  1. Open Notepad++ then copy your content
  2. Press ctrl + h
  3. Find what is should be ,(comma) or any character that you want to replace
  4. Replace with should be \n
  5. Select Search Mode -> Extended (\n, \r, \t, \0)
  6. Then Click on Replace All

Contain form within a bootstrap popover?

like this Working demo http://jsfiddle.net/7e2XU/21/show/# * Update: http://jsfiddle.net/kz5kjmbt/

 <div class="container">
    <div class="row" style="padding-top: 240px;"> <a href="#" class="btn btn-large btn-primary" rel="popover" data-content='
<form id="mainForm" name="mainForm" method="post" action="">
    <p>
        <label>Name :</label>
        <input type="text" id="txtName" name="txtName" />
    </p>
    <p>
        <label>Address 1 :</label>
        <input type="text" id="txtAddress" name="txtAddress" />
    </p>
    <p>
        <label>City :</label>
        <input type="text" id="txtCity" name="txtCity" />
    </p>
    <p>
        <input type="submit" name="Submit" value="Submit" />
    </p>
</form>
 data-placement="top" data-original-title="Fill in form">Open form</a>

    </div>
</div>

JavaScript code:

    $('a[rel=popover]').popover({
      html: 'true',
      placement: 'right'
    })

ScreenShot

working updated fiddle screenshot

"unadd" a file to svn before commit

Full process (Unix svn package):

Check files are not in SVN:

> svn st -u folder 
? folder

Add all (including ignored files):

> svn add folder
A   folder
A   folder/file1.txt
A   folder/folder2
A   folder/folder2/file2.txt
A   folder/folderToIgnore
A   folder/folderToIgnore/fileToIgnore1.txt
A   fileToIgnore2.txt

Remove "Add" Flag to All * Ignore * files:

> cd folder

> svn revert --recursive folderToIgnore
Reverted 'folderToIgnore'
Reverted 'folderToIgnore/fileToIgnore1.txt'


> svn revert fileToIgnore2.txt
Reverted 'fileToIgnore2.txt'

Edit svn ignore on folder

svn propedit svn:ignore .

Add two singles lines with just the following:

folderToIgnore
fileToIgnore2.txt

Check which files will be upload and commit:

> cd ..

> svn st -u
A   folder
A   folder/file1.txt
A   folder/folder2
A   folder/folder2/file2.txt


> svn ci -m "Commit message here"

PHP AES encrypt / decrypt

Please use an existing secure PHP encryption library

It's generally a bad idea to write your own cryptography unless you have experience breaking other peoples' cryptography implementations.

None of the examples here authenticate the ciphertext, which leaves them vulnerable to bit-rewriting attacks.

If you can install PECL extensions, libsodium is even better

<?php
// PECL libsodium 0.2.1 and newer

/**
 * Encrypt a message
 * 
 * @param string $message - message to encrypt
 * @param string $key - encryption key
 * @return string
 */
function safeEncrypt($message, $key)
{
    $nonce = \Sodium\randombytes_buf(
        \Sodium\CRYPTO_SECRETBOX_NONCEBYTES
    );

    return base64_encode(
        $nonce.
        \Sodium\crypto_secretbox(
            $message,
            $nonce,
            $key
        )
    );
}

/**
 * Decrypt a message
 * 
 * @param string $encrypted - message encrypted with safeEncrypt()
 * @param string $key - encryption key
 * @return string
 */
function safeDecrypt($encrypted, $key)
{   
    $decoded = base64_decode($encrypted);
    $nonce = mb_substr($decoded, 0, \Sodium\CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
    $ciphertext = mb_substr($decoded, \Sodium\CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');

    return \Sodium\crypto_secretbox_open(
        $ciphertext,
        $nonce,
        $key
    );
}    

Then to test it out:

<?php
// This refers to the previous code block.
require "safeCrypto.php"; 

// Do this once then store it somehow:
$key = \Sodium\randombytes_buf(\Sodium\CRYPTO_SECRETBOX_KEYBYTES);
$message = 'We are all living in a yellow submarine';

$ciphertext = safeEncrypt($message, $key);
$plaintext = safeDecrypt($ciphertext, $key);

var_dump($ciphertext);
var_dump($plaintext);

This can be used in any situation where you are passing data to the client (e.g. encrypted cookies for sessions without server-side storage, encrypted URL parameters, etc.) with a reasonably high degree of certainty that the end user cannot decipher or reliably tamper with it.

Since libsodium is cross-platform, this also makes it easier to communicate with PHP from, e.g. Java applets or native mobile apps.


Note: If you specifically need to add encrypted cookies powered by libsodium to your app, my employer Paragon Initiative Enterprises is developing a library called Halite that does all of this for you.

How to determine the screen width in terms of dp or dip at runtime in Android?

Try this:

Display display   = getWindowManager().getDefaultDisplay();
Point displaySize = new Point();
display.getSize(displaySize);
int width  = displaySize.x;
int height = displaySize.y;

How to get the azure account tenant Id?

This answer was provided on Microsoft's website, last updated on 3/21/2018:

https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal

In short, here are the screenshots from the walkthrough:

  1. Select Azure Active Directory.

Azure Active Directory

  1. To get the tenant ID, select Properties for your Azure AD tenant.

Select Properties

  1. Copy the Directory ID. This value is your tenant ID.

Copy the Directory ID, this is the tenant ID.

Hope this helps.

Practical uses of git reset --soft?

SourceTree is a git GUI which has a pretty convenient interface for staging just the bits you want. It does not have anything remotely similar for amending a proper revision.

So git reset --soft HEAD~1 is much more useful than commit --amend in this scenario. I can undo the commit, get all the changes back into the staging area, and resume tweaking the staged bits using SourceTree.

Really, it seems to me that commit --amend is the more redundant command of the two, but git is git and does not shy away from similar commands that do slightly different things.

How to clear mysql screen console in windows?

you can type the following step:

mysql> exit;

C:\xampp\mysql\bin> cls

C:\xampp\mysql\bin> mysql -u root -h localhost

it's work!

Controlling number of decimal digits in print output in R

One more solution able to control the how many decimal digits to print out based on needs (if you don't want to print redundant zero(s))

For example, if you have a vector as elements and would like to get sum of it

elements <- c(-1e-05, -2e-04, -3e-03, -4e-02, -5e-01, -6e+00, -7e+01, -8e+02)
sum(elements)
## -876.5432

Apparently, the last digital as 1 been truncated, the ideal result should be -876.54321, but if set as fixed printing decimal option, e.g sprintf("%.10f", sum(elements)), redundant zero(s) generate as -876.5432100000

Following the tutorial here: printing decimal numbers, if able to identify how many decimal digits in the certain numeric number, like here in -876.54321, there are 5 decimal digits need to print, then we can set up a parameter for format function as below:

decimal_length <- 5
formatC(sum(elements), format = "f", digits = decimal_length)
## -876.54321

We can change the decimal_length based on each time query, so it can satisfy different decimal printing requirement.

JavaScript adding decimal numbers issue

This is common issue with floating points.

Use toFixed in combination with parseFloat.

Here is example in JavaScript:

function roundNumber(number, decimals) {
    var newnumber = new Number(number+'').toFixed(parseInt(decimals));
    return parseFloat(newnumber); 
}

0.1 + 0.2;                    //=> 0.30000000000000004
roundNumber( 0.1 + 0.2, 12 ); //=> 0.3

Swapping pointers in C (char, int)

void intSwap (int *pa, int *pb){
    int temp = *pa;
    *pa = *pb;
    *pb = temp;
}

You need to know the following -

int a = 5; // an integer, contains value
int *p; // an integer pointer, contains address
p = &a; // &a means address of a
a = *p; // *p means value stored in that address, here 5

void charSwap(char* a, char* b){
    char temp = *a;
    *a = *b;
    *b = temp;
}

So, when you swap like this. Only the value will be swapped. So, for a char* only their first char will swap.

Now, if you understand char* (string) clearly, then you should know that, you only need to exchange the pointer. It'll be easier to understand if you think it as an array instead of string.

void stringSwap(char** a, char** b){
    char *temp = *a;
    *a = *b;
    *b = temp;
}

So, here you are passing double pointer because starting of an array itself is a pointer.

Laravel Soft Delete posts

In the Latest version of Laravel i.e above Laravel 5.0. It is quite simple to perform this task. In Model, inside the class just write 'use SoftDeletes'. Example

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model
{
    use SoftDeletes;
}

And In Controller, you can do deletion. Example

User::where('email', '[email protected]')->delete();

or

User::where('email', '[email protected]')->softDeletes();

Make sure that you must have 'deleted_at' column in the users Table.

Semi-transparent color layer over background-image?

Here is a more simple trick with only css.

_x000D_
_x000D_
<div class="background"> </div>_x000D_
    <style>_x000D_
    .background {_x000D_
      position:relative;_x000D_
      height:50px;_x000D_
      background-color: rgba(248, 247, 216, 0.7);_x000D_
      background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAJElEQVQYV2NctWrVfwYkEBYWxojMZ6SDAmT7QGx0K1EcRBsFAADeG/3M/HteAAAAAElFTkSuQmCC); _x000D_
    }_x000D_
_x000D_
    .background:after {_x000D_
        content:" ";_x000D_
        background-color:inherit;_x000D_
        position: absolute;_x000D_
        top: 0;_x000D_
        left: 0;_x000D_
        width: 100%;_x000D_
        height: 100%; _x000D_
    }_x000D_
_x000D_
    </style>
_x000D_
_x000D_
_x000D_

How to center the elements in ConstraintLayout

just add

android:gravity="center"

and done :)

python time + timedelta equivalent

This is a bit nasty, but:

from datetime import datetime, timedelta

now = datetime.now().time()
# Just use January the first, 2000
d1 = datetime(2000, 1, 1, now.hour, now.minute, now.second)
d2 = d1 + timedelta(hours=1, minutes=23)
print d2.time()