Programs & Examples On #Xmodem

Substring with reverse index

here is my custom function

function reverse_substring(str,from,to){
  var temp="";
  var i=0;
  var pos = 0;
  var append;      
  for(i=str.length-1;i>=0;i--){
    //alert("inside loop " + str[i]);
    if(pos == from){
         append=true;
    }

    if(pos == to){
         append=false;
         break;
    }
    if(append){
         temp = str[i] + temp;
    }
    pos++;
  }
  alert("bottom loop " + temp);
}

var str = "bala_123";
reverse_substring(str,0,3);

This function works for reverse index.

Updating records codeigniter

In your Controller

public function updtitle() 
{   
    $data = array(
        'table_name' => 'your_table_name_to_update', // pass the real table name
        'id' => $this->input->post('id'),
        'title' => $this->input->post('title')
    );

    $this->load->model('Updmodel'); // load the model first
    if($this->Updmodel->upddata($data)) // call the method from the model
    {
        // update successful
    }
    else
    {
        // update not successful
    }

}

In Your Model

public function upddata($data) {
    extract($data);
    $this->db->where('emp_no', $id);
    $this->db->update($table_name, array('title' => $title));
    return true;
}

The active record query is similar to

"update $table_name set title='$title' where emp_no=$id"

Spring Boot - How to log all requests and responses with exceptions in single place?

Spring already provides a filter that does this job. Add following bean to your config

@Bean
public CommonsRequestLoggingFilter requestLoggingFilter() {
    CommonsRequestLoggingFilter loggingFilter = new CommonsRequestLoggingFilter();
    loggingFilter.setIncludeClientInfo(true);
    loggingFilter.setIncludeQueryString(true);
    loggingFilter.setIncludePayload(true);
    loggingFilter.setMaxPayloadLength(64000);
    return loggingFilter;
}

Don't forget to change log level of org.springframework.web.filter.CommonsRequestLoggingFilter to DEBUG.

Git - How to fix "corrupted" interactive rebase?

In my case after testing all this options and still having issues i tried sudo git rebase --abort and it did the whole thing

Passing data to components in vue.js

-------------Following is applicable only to Vue 1 --------------

Passing data can be done in multiple ways. The method depends on the type of use.


If you want to pass data from your html while you add a new component. That is done using props.

<my-component prop-name="value"></my-component>

This prop value will be available to your component only if you add the prop name prop-name to your props attribute.


When data is passed from a component to another component because of some dynamic or static event. That is done by using event dispatchers and broadcasters. So for example if you have a component structure like this:

<my-parent>
    <my-child-A></my-child-A>
    <my-child-B></my-child-B>
</my-parent>

And you want to send data from <my-child-A> to <my-child-B> then in <my-child-A> you will have to dispatch an event:

this.$dispatch('event_name', data);

This event will travel all the way up the parent chain. And from whichever parent you have a branch toward <my-child-B> you broadcast the event along with the data. So in the parent:

events:{
    'event_name' : function(data){
        this.$broadcast('event_name', data);
    },

Now this broadcast will travel down the child chain. And at whichever child you want to grab the event, in our case <my-child-B> we will add another event:

events: {
    'event_name' : function(data){
        // Your code. 
    },
},

The third way to pass data is through parameters in v-links. This method is used when components chains are completely destroyed or in cases when the URI changes. And i can see you already understand them.


Decide what type of data communication you want, and choose appropriately.

How do you rebase the current branch's changes on top of changes being merged in?

You've got what rebase does backwards. git rebase master does what you're asking for — takes the changes on the current branch (since its divergence from master) and replays them on top of master, then sets the head of the current branch to be the head of that new history. It doesn't replay the changes from master on top of the current branch.

How to lowercase a pandas dataframe string column if it has missing values?

Pandas >= 0.25: Remove Case Distinctions with str.casefold

Starting from v0.25, I recommend using the "vectorized" string method str.casefold if you're dealing with unicode data (it works regardless of string or unicodes):

s = pd.Series(['lower', 'CAPITALS', np.nan, 'SwApCaSe'])
s.str.casefold()

0       lower
1    capitals
2         NaN
3    swapcase
dtype: object

Also see related GitHub issue GH25405.

casefold lends itself to more aggressive case-folding comparison. It also handles NaNs gracefully (just as str.lower does).

But why is this better?

The difference is seen with unicodes. Taking the example in the python str.casefold docs,

Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter 'ß' is equivalent to "ss". Since it is already lowercase, lower() would do nothing to 'ß'; casefold() converts it to "ss".

Compare the output of lower for,

s = pd.Series(["der Fluß"])
s.str.lower()

0    der fluß
dtype: object

Versus casefold,

s.str.casefold()

0    der fluss
dtype: object

Also see Python: lower() vs. casefold() in string matching and converting to lowercase.

Why do this() and super() have to be the first statement in a constructor?

I've found a way around this by chaining constructors and static methods. What I wanted to do looked something like this:

public class Foo extends Baz {
  private final Bar myBar;

  public Foo(String arg1, String arg2) {
    // ...
    // ... Some other stuff needed to construct a 'Bar'...
    // ...
    final Bar b = new Bar(arg1, arg2);
    super(b.baz()):
    myBar = b;
  }
}

So basically construct an object based on constructor parameters, store the object in a member, and also pass the result of a method on that object into super's constructor. Making the member final was also reasonably important as the nature of the class is that it's immutable. Note that as it happens, constructing Bar actually takes a few intermediate objects, so it's not reducible to a one-liner in my actual use case.

I ended up making it work something like this:

public class Foo extends Baz {
  private final Bar myBar;

  private static Bar makeBar(String arg1,  String arg2) {
    // My more complicated setup routine to actually make 'Bar' goes here...
    return new Bar(arg1, arg2);
  }

  public Foo(String arg1, String arg2) {
    this(makeBar(arg1, arg2));
  }

  private Foo(Bar bar) {
    super(bar.baz());
    myBar = bar;
  }
}

Legal code, and it accomplishes the task of executing multiple statements before calling the super constructor.

How do I create an iCal-type .ics file that can be downloaded by other users?

That will work just fine. You can export an entire calendar with File > Export…, or individual events by dragging them to the Finder.

iCalendar (.ics) files are human-readable, so you can always pop it open in a text editor to make sure no private events made it in there. They consist of nested sections with start with BEGIN: and end with END:. You'll mostly find VEVENT sections (each of which represents an event) and VTIMEZONE sections, each of which represents a time zone that's referenced from one or more events.

Redis strings vs Redis hashes to represent JSON: efficiency?

Some additions to a given set of answers:

First of all if you going to use Redis hash efficiently you must know a keys count max number and values max size - otherwise if they break out hash-max-ziplist-value or hash-max-ziplist-entries Redis will convert it to practically usual key/value pairs under a hood. ( see hash-max-ziplist-value, hash-max-ziplist-entries ) And breaking under a hood from a hash options IS REALLY BAD, because each usual key/value pair inside Redis use +90 bytes per pair.

It means that if you start with option two and accidentally break out of max-hash-ziplist-value you will get +90 bytes per EACH ATTRIBUTE you have inside user model! ( actually not the +90 but +70 see console output below )

 # you need me-redis and awesome-print gems to run exact code
 redis = Redis.include(MeRedis).configure( hash_max_ziplist_value: 64, hash_max_ziplist_entries: 512 ).new 
  => #<Redis client v4.0.1 for redis://127.0.0.1:6379/0> 
 > redis.flushdb
  => "OK" 
 > ap redis.info(:memory)
    {
                "used_memory" => "529512",
          **"used_memory_human" => "517.10K"**,
            ....
    }
  => nil 
 # me_set( 't:i' ... ) same as hset( 't:i/512', i % 512 ... )    
 # txt is some english fictionary book around 56K length, 
 # so we just take some random 63-symbols string from it 
 > redis.pipelined{ 10000.times{ |i| redis.me_set( "t:#{i}", txt[rand(50000), 63] ) } }; :done
 => :done 
 > ap redis.info(:memory)
  {
               "used_memory" => "1251944",
         **"used_memory_human" => "1.19M"**, # ~ 72b per key/value
            .....
  }
  > redis.flushdb
  => "OK" 
  # setting **only one value** +1 byte per hash of 512 values equal to set them all +1 byte 
  > redis.pipelined{ 10000.times{ |i| redis.me_set( "t:#{i}", txt[rand(50000), i % 512 == 0 ? 65 : 63] ) } }; :done 
  > ap redis.info(:memory)
   {
               "used_memory" => "1876064",
         "used_memory_human" => "1.79M",   # ~ 134 bytes per pair  
          ....
   }
    redis.pipelined{ 10000.times{ |i| redis.set( "t:#{i}", txt[rand(50000), 65] ) } };
    ap redis.info(:memory)
    {
             "used_memory" => "2262312",
          "used_memory_human" => "2.16M", #~155 byte per pair i.e. +90 bytes    
           ....
    }

For TheHippo answer, comments on Option one are misleading:

hgetall/hmset/hmget to the rescue if you need all fields or multiple get/set operation.

For BMiner answer.

Third option is actually really fun, for dataset with max(id) < has-max-ziplist-value this solution has O(N) complexity, because, surprise, Reddis store small hashes as array-like container of length/key/value objects!

But many times hashes contain just a few fields. When hashes are small we can instead just encode them in an O(N) data structure, like a linear array with length-prefixed key value pairs. Since we do this only when N is small, the amortized time for HGET and HSET commands is still O(1): the hash will be converted into a real hash table as soon as the number of elements it contains will grow too much

But you should not worry, you'll break hash-max-ziplist-entries very fast and there you go you are now actually at solution number 1.

Second option will most likely go to the fourth solution under a hood because as question states:

Keep in mind that if I use a hash, the value length isn't predictable. They're not all short such as the bio example above.

And as you already said: the fourth solution is the most expensive +70 byte per each attribute for sure.

My suggestion how to optimize such dataset:

You've got two options:

  1. If you cannot guarantee max size of some user attributes than you go for first solution and if memory matter is crucial than compress user json before store in redis.

  2. If you can force max size of all attributes. Than you can set hash-max-ziplist-entries/value and use hashes either as one hash per user representation OR as hash memory optimization from this topic of a Redis guide: https://redis.io/topics/memory-optimization and store user as json string. Either way you may also compress long user attributes.

.datepicker('setdate') issues, in jQuery

When you trying to call setDate you must provide valid javascript Date object.

queryDate = '2009-11-01';

var parsedDate = $.datepicker.parseDate('yy-mm-dd', queryDate);

$('#datePicker').datepicker('setDate', parsedDate);

This will allow you to use different formats for query date and string date representation in datepicker. This approach is very helpful when you create multilingual site. Another helpful function is formatDate, which formats javascript date object to string.

$.datepicker.formatDate( format, date, settings );

Maven error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

Me too faced the similar issue. But in my case I used apache-maven-3.3.3-src folder in path variables. Later I corrected those with correct path of folder apache-maven-3.3.3-bin. This resolved the issue. Am not telling that is the same error reported here but this way also you can get this error and rectify it. That is what I am trying to say here.

How do I set the path to a DLL file in Visual Studio?

I had the same problem and my problem had nothing to do with paths. One of my dll-s was written in c++ and it turnes out that if your visual studio doesn't know how to open a dll file it will say that it did not find it. What i did was locate which dll it did not find, than searched for that dll in my directories and opened it in a separate visual studio window. When trying to navigate through Solution explorer of that project, visual studio said that it cannot show what is inside and that i need some extra extensions, so that it can open those files. Surely enough, after installing the recomended extension (in my case something to do with c++) the

"This application has failed to start because xxx.dll was not found."

error miraculously dissapeared.

Overriding the java equals() method - not working?

In Java, the equals() method that is inherited from Object is:

public boolean equals(Object other);

In other words, the parameter must be of type Object. This is called overriding; your method public boolean equals(Book other) does what is called overloading to the equals() method.

The ArrayList uses overridden equals() methods to compare contents (e.g. for its contains() and equals() methods), not overloaded ones. In most of your code, calling the one that didn't properly override Object's equals was fine, but not compatible with ArrayList.

So, not overriding the method correctly can cause problems.

I override equals the following everytime:

@Override
public boolean equals(Object other){
    if (other == null) return false;
    if (other == this) return true;
    if (!(other instanceof MyClass)) return false;
    MyClass otherMyClass = (MyClass)other;
    ...test other properties here...
}

The use of the @Override annotation can help a ton with silly mistakes.

Use it whenever you think you are overriding a super class' or interface's method. That way, if you do it the wrong way, you will get a compile error.

How to move screen without moving cursor in Vim?

I've used these shortcuts in the past (note: separate key strokes i.e. tap z, let go, tap the subsequent key):

z enter --> moves current line to top of screen

z . --> moves current line to center of screen

z - --> moves current line to bottom

If it's not obvious:

enter means the Return or Enter key.

. means the DOT or "full stop" key (.).

- means the HYPHEN key (-)

For what it's worth, z. avoids the danger of saving and closing Vi by accidentally typing ZZ if the caps-lock is on.

PDO closing connection

<?php if(!class_exists('PDO2')) {
    class PDO2 {
        private static $_instance;
        public static function getInstance() {
            if (!isset(self::$_instance)) {
                try {
                    self::$_instance = new PDO(
                        'mysql:host=***;dbname=***',
                        '***',
                        '***',
                        array(
                            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_general_ci",
                            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION
                        )
                    );
                } catch (PDOException $e) {
                    throw new PDOException($e->getMessage(), (int) $e->getCode());
                }
            }
            return self::$_instance;
        }
        public static function closeInstance() {
            return self::$_instance = null;
        }
    }
}
$req = PDO2::getInstance()->prepare('SELECT * FROM table');
$req->execute();
$count = $req->rowCount();
$results = $req->fetchAll(PDO::FETCH_ASSOC);
$req->closeCursor();
// Do other requests maybe
// And close connection
PDO2::closeInstance();
// print output

Full example, with custom class PDO2.

How to add "active" class to Html.ActionLink in ASP.NET MVC

I know this question is old, but I will just like to add my voice here. I believe it is a good idea to leave the knowledge of whether or not a link is active to the controller of the view.

I would just set a unique value for each view in the controller action. For instance, if I wanted to make the home page link active, I would do something like this:

public ActionResult Index()
{            
    ViewBag.Title = "Home";
    ViewBag.Home = "class = active";
    return View();
}

Then in my view, I will write something like this:

<li @ViewBag.Home>@Html.ActionLink("Home", "Index", "Home", null, new { title = "Go home" })</li>

When you navigate to a different page, say Programs, ViewBag.Home does not exist (instead ViewBag.Programs does); therefore, nothing is rendered, not even class="". I think this is cleaner both for maintainability and cleanliness. I tend to always want to leave logic out of the view as much as I can.

Converting RGB to grayscale/intensity

is all this really necessary, human perception and CRT vs LCD will vary, but the R G B intensity does not, Why not L = (R + G + B)/3 and set the new RGB to L, L, L?

UPDATE and REPLACE part of a string

CREATE TABLE tbl_PersonalDetail
(ID INT IDENTITY ,[Date] nvarchar(20), Name nvarchar(20), GenderID int);

INSERT INTO Tbl_PersonalDetail VALUES(N'18-4-2015', N'Monay', 2),
                                     (N'31-3-2015', N'Monay', 2),
                                     (N'28-12-2015', N'Monay', 2),
                                     (N'19-4-2015', N'Monay', 2)

DECLARE @Date Nvarchar(200)

SET @Date = (SELECT [Date] FROM Tbl_PersonalDetail WHERE ID = 2)

Update Tbl_PersonalDetail SET [Date] = (REPLACE(@Date , '-','/')) WHERE ID = 2 

jQuery change event on dropdown

You should've kept that DOM ready function

$(function() {
    $("#projectKey").change(function() {
        alert( $('option:selected', this).text() );
    });
});

The document isn't ready if you added the javascript before the elements in the DOM, you have to either use a DOM ready function or add the javascript after the elements, the usual place is right before the </body> tag

Retrieve data from website in android app

You can use jsoup to parse any kind of web page. Here you can find the jsoup library and full source code.

Here is an example: http://desicoding.blogspot.com/2011/03/how-to-parse-html-in-java-jsoup.html

To install in Eclipse:

  1. Right Click on project
  2. BuildPath
  3. Add External Archives
  4. select the .jar file

You can parse according to tag/parent/child very comfortably

PL/SQL print out ref cursor returned by a stored procedure

If you want to print all the columns in your select clause you can go with the autoprint command.

CREATE OR REPLACE PROCEDURE sps_detail_dtest(v_refcur OUT sys_refcursor)
AS
BEGIN
  OPEN v_refcur FOR 'select * from dummy_table';
END;

SET autoprint on;

--calling the procedure
VAR vcur refcursor;
DECLARE 
BEGIN
  sps_detail_dtest(vrefcur=>:vcur);
END;

Hope this gives you an alternate solution

How to add custom html attributes in JSX

uniqueId is custom attribute.

<a {...{ "uniqueId": `${item.File.UniqueId}` }}  href={item.File.ServerRelativeUrl} target='_blank'>{item.File.Name}</a>

No increment operator (++) in Ruby?

Ruby has no pre/post increment/decrement operator. For instance, x++ or x-- will fail to parse. More importantly, ++x or --x will do nothing! In fact, they behave as multiple unary prefix operators: -x == ---x == -----x == ...... To increment a number, simply write x += 1.

Taken from "Things That Newcomers to Ruby Should Know " (archive, mirror)

That explains it better than I ever could.

EDIT: and the reason from the language author himself (source):

  1. ++ and -- are NOT reserved operator in Ruby.
  2. C's increment/decrement operators are in fact hidden assignment. They affect variables, not objects. You cannot accomplish assignment via method. Ruby uses +=/-= operator instead.
  3. self cannot be a target of assignment. In addition, altering the value of integer 1 might cause severe confusion throughout the program.

ImportError: Couldn't import Django

I think the best way to use django is with virtualenv it's safe and you can install many apps in virtualenv which does not affect any outer space of the system vitualenv uses the default version of python which is same as in your system to install virtualenv

sudo pip install virtualenv

or for python3

sudo pip3 install virtualenv

and then in your dir

mkdir ~/newproject

cd ~/newproject

Now, create a virtual environment within the project directory by typing

virtualenv newenv

To install packages into the isolated environment, you must activate it by typing:

source newenv/bin/activate

now install here with

pip install django

You can verify the installation by typing:

django-admin --version

To leave your virtual environment, you need to issue the deactivate command from anywhere on the system:

deactivate

Sorting a Dictionary in place with respect to keys

The correct answer is already stated (just use SortedDictionary).

However, if by chance you have some need to retain your collection as Dictionary, it is possible to access the Dictionary keys in an ordered way, by, for example, ordering the keys in a List, then using this list to access the Dictionary. An example...

Dictionary<string, int> dupcheck = new Dictionary<string, int>();

...some code that fills in "dupcheck", then...

if (dupcheck.Count > 0) {
  Console.WriteLine("\ndupcheck (count: {0})\n----", dupcheck.Count);
  var keys_sorted = dupcheck.Keys.ToList();
    keys_sorted.Sort();
  foreach (var k in keys_sorted) {
    Console.WriteLine("{0} = {1}", k, dupcheck[k]);
  }
}

Don't forget using System.Linq; for this.

Sum up a column from a specific row down

This seems like the easiest (but not most robust) way to me. Simply compute the sum from row 6 to the maximum allowed row number, as specified by Excel. According to this site, the maximum is currently 1048576, so the following should work for you:

=sum(c6:c1048576)

For more robust solutions, see the other answers.

Find first element by predicate

No, filter does not scan the whole stream. It's an intermediate operation, which returns a lazy stream (actually all intermediate operations return a lazy stream). To convince you, you can simply do the following test:

List<Integer> list = Arrays.asList(1, 10, 3, 7, 5);
int a = list.stream()
            .peek(num -> System.out.println("will filter " + num))
            .filter(x -> x > 5)
            .findFirst()
            .get();
System.out.println(a);

Which outputs:

will filter 1
will filter 10
10

You see that only the two first elements of the stream are actually processed.

So you can go with your approach which is perfectly fine.

R Markdown - changing font size and font type in html output

You can change the font size in R Markdown with HTML code tags <font size="1"> your text </font> . This code is added to the R Markdown document and will alter the output of the HTML output.

For example:

_x000D_
_x000D_
 <font size="1"> This is my text number1</font> _x000D_
_x000D_
 <font size="2"> This is my text number 2 </font>_x000D_
 _x000D_
 <font size="3"> This is my text number 3</font> _x000D_
 _x000D_
 <font size="4"> This is my text number 4</font> _x000D_
 _x000D_
 <font size="5"> This is my text number 5</font> _x000D_
 _x000D_
 <font size="6"> This is my text number 6</font>
_x000D_
_x000D_
_x000D_

PHP code to convert a MySQL query to CSV

// Export to CSV
if($_GET['action'] == 'export') {

  $rsSearchResults = mysql_query($sql, $db) or die(mysql_error());

  $out = '';
  $fields = mysql_list_fields('database','table',$db);
  $columns = mysql_num_fields($fields);

  // Put the name of all fields
  for ($i = 0; $i < $columns; $i++) {
    $l=mysql_field_name($fields, $i);
    $out .= '"'.$l.'",';
  }
  $out .="\n";

  // Add all values in the table
  while ($l = mysql_fetch_array($rsSearchResults)) {
    for ($i = 0; $i < $columns; $i++) {
      $out .='"'.$l["$i"].'",';
    }
    $out .="\n";
  }
  // Output to browser with appropriate mime type, you choose ;)
  header("Content-type: text/x-csv");
  //header("Content-type: text/csv");
  //header("Content-type: application/csv");
  header("Content-Disposition: attachment; filename=search_results.csv");
  echo $out;
  exit;
}

How to listen state changes in react.js?

In 2020 you can listen state changes with useEffect hook like this

export function MyComponent(props) {
    const [myState, setMystate] = useState('initialState')

    useEffect(() => {
        console.log(myState, '- Has changed')
    },[myState]) // <-- here put the parameter to listen
}

How are software license keys generated?

I've not got any experience with what people actually do to generate CD keys, but (assuming you're not wanting to go down the road of online activation) here are a few ways one could make a key:

  • Require that the number be divisible by (say) 17. Trivial to guess, if you have access to many keys, but the majority of potential strings will be invalid. Similar would be requiring that the checksum of the key match a known value.

  • Require that the first half of the key, when concatenated with a known value, hashes down to the second half of the key. Better, but the program still contains all the information needed to generate keys as well as to validate them.

  • Generate keys by encrypting (with a private key) a known value + nonce. This can be verified by decrypting using the corresponding public key and verifying the known value. The program now has enough information to verify the key without being able to generate keys.

These are still all open to attack: the program is still there and can be patched to bypass the check. Cleverer might be to encrypt part of the program using the known value from my third method, rather than storing the value in the program. That way you'd have to find a copy of the key before you could decrypt the program, but it's still vulnerable to being copied once decrypted and to having one person take their legit copy and use it to enable everyone else to access the software.

Binding an Image in WPF MVVM

Displaying an Image in WPF is much easier than that. Try this:

<Image Source="{Binding DisplayedImagePath}" HorizontalAlignment="Left" 
    Margin="0,0,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Bottom" 
    Grid.Row="8" Width="200"  Grid.ColumnSpan="2" />

And the property can just be a string:

public string DisplayedImage 
{
    get { return @"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg"; }
}

Although you really should add your images to a folder named Images in the root of your project and set their Build Action to Resource in the Properties Window in Visual Studio... you could then access them using this format:

public string DisplayedImage 
{
    get { return "/AssemblyName;component/Images/ImageName.jpg"; }
}

UPDATE >>>

As a final tip... if you ever have a problem with a control not working as expected, simply type 'WPF', the name of that control and then the word 'class' into a search engine. In this case, you would have typed 'WPF Image Class'. The top result will always be MSDN and if you click on the link, you'll find out all about that control and most pages have code examples as well.


UPDATE 2 >>>

If you followed the examples from the link to MSDN and it's not working, then your problem is not the Image control. Using the string property that I suggested, try this:

<StackPanel>
    <Image Source="{Binding DisplayedImagePath}" />
    <TextBlock Text="{Binding DisplayedImagePath}" />
</StackPanel>

If you can't see the file path in the TextBlock, then you probably haven't set your DataContext to the instance of your view model. If you can see the text, then the problem is with your file path.


UPDATE 3 >>>

In .NET 4, the above Image.Source values would work. However, Microsoft made some horrible changes in .NET 4.5 that broke many different things and so in .NET 4.5, you'd need to use the full pack path like this:

<Image Source="pack://application:,,,/AssemblyName;component/Images/image_to_use.png">

For further information on pack URIs, please see the Pack URIs in WPF page on Microsoft Docs.

Create a copy of a table within the same database DB2

Try this:

CREATE TABLE SCHEMA.NEW_TB LIKE SCHEMA.OLD_TB;
INSERT INTO SCHEMA.NEW_TB (SELECT * FROM SCHEMA.OLD_TB);

Options that are not copied include:

  • Check constraints
  • Column default values
  • Column comments
  • Foreign keys
  • Logged and compact option on BLOB columns
  • Distinct types

Iterator invalidation rules

C++17 (All references are from the final working draft of CPP17 - n4659)


Insertion

Sequence Containers

  • vector: The functions insert, emplace_back, emplace, push_back cause reallocation if the new size is greater than the old capacity. Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. If no reallocation happens, all the iterators and references before the insertion point remain valid. [26.3.11.5/1]
    With respect to the reserve function, reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. No reallocation shall take place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the value of capacity(). [26.3.11.3/6]

  • deque: An insertion in the middle of the deque invalidates all the iterators and references to elements of the deque. An insertion at either end of the deque invalidates all the iterators to the deque, but has no effect on the validity of references to elements of the deque. [26.3.8.4/1]

  • list: Does not affect the validity of iterators and references. If an exception is thrown there are no effects. [26.3.10.4/1].
    The insert, emplace_front, emplace_back, emplace, push_front, push_back functions are covered under this rule.

  • forward_list: None of the overloads of insert_after shall affect the validity of iterators and references [26.3.9.5/1]

  • array: As a rule, iterators to an array are never invalidated throughout the lifetime of the array. One should take note, however, that during swap, the iterator will continue to point to the same array element, and will thus change its value.

Associative Containers

  • All Associative Containers: The insert and emplace members shall not affect the validity of iterators and references to the container [26.2.6/9]

Unordered Associative Containers

  • All Unordered Associative Containers: Rehashing invalidates iterators, changes ordering between elements, and changes which buckets elements appear in, but does not invalidate pointers or references to elements. [26.2.7/9]
    The insert and emplace members shall not affect the validity of references to container elements, but may invalidate all iterators to the container. [26.2.7/14]
    The insert and emplace members shall not affect the validity of iterators if (N+n) <= z * B, where N is the number of elements in the container prior to the insert operation, n is the number of elements inserted, B is the container’s bucket count, and z is the container’s maximum load factor. [26.2.7/15]

  • All Unordered Associative Containers: In case of a merge operation (e.g., a.merge(a2)), iterators referring to the transferred elements and all iterators referring to a will be invalidated, but iterators to elements remaining in a2 will remain valid. (Table 91 — Unordered associative container requirements)

Container Adaptors

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

Erasure

Sequence Containers

  • vector: The functions erase and pop_back invalidate iterators and references at or after the point of the erase. [26.3.11.5/3]

  • deque: An erase operation that erases the last element of a deque invalidates only the past-the-end iterator and all iterators and references to the erased elements. An erase operation that erases the first element of a deque but not the last element invalidates only iterators and references to the erased elements. An erase operation that erases neither the first element nor the last element of a deque invalidates the past-the-end iterator and all iterators and references to all the elements of the deque. [ Note: pop_front and pop_back are erase operations. —end note ] [26.3.8.4/4]

  • list: Invalidates only the iterators and references to the erased elements. [26.3.10.4/3]. This applies to erase, pop_front, pop_back, clear functions.
    remove and remove_if member functions: Erases all the elements in the list referred by a list iterator i for which the following conditions hold: *i == value, pred(*i) != false. Invalidates only the iterators and references to the erased elements [26.3.10.5/15].
    unique member function - Erases all but the first element from every consecutive group of equal elements referred to by the iterator i in the range [first + 1, last) for which *i == *(i-1) (for the version of unique with no arguments) or pred(*i, *(i - 1)) (for the version of unique with a predicate argument) holds. Invalidates only the iterators and references to the erased elements. [26.3.10.5/19]

  • forward_list: erase_after shall invalidate only iterators and references to the erased elements. [26.3.9.5/1].
    remove and remove_if member functions - Erases all the elements in the list referred by a list iterator i for which the following conditions hold: *i == value (for remove()), pred(*i) is true (for remove_if()). Invalidates only the iterators and references to the erased elements. [26.3.9.6/12].
    unique member function - Erases all but the first element from every consecutive group of equal elements referred to by the iterator i in the range [first + 1, last) for which *i == *(i-1) (for the version with no arguments) or pred(*i, *(i - 1)) (for the version with a predicate argument) holds. Invalidates only the iterators and references to the erased elements. [26.3.9.6/16]

  • All Sequence Containers: clear invalidates all references, pointers, and iterators referring to the elements of a and may invalidate the past-the-end iterator (Table 87 — Sequence container requirements). But for forward_list, clear does not invalidate past-the-end iterators. [26.3.9.5/32]

  • All Sequence Containers: assign invalidates all references, pointers and iterators referring to the elements of the container. For vector and deque, also invalidates the past-the-end iterator. (Table 87 — Sequence container requirements)

Associative Containers

  • All Associative Containers: The erase members shall invalidate only iterators and references to the erased elements [26.2.6/9]

  • All Associative Containers: The extract members invalidate only iterators to the removed element; pointers and references to the removed element remain valid [26.2.6/10]

Container Adaptors

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

General container requirements relating to iterator invalidation:

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

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

As examples of the above requirements:

  • transform algorithm: The op and binary_op functions shall not invalidate iterators or subranges, or modify elements in the ranges [28.6.4/1]

  • accumulate algorithm: In the range [first, last], binary_op shall neither modify elements nor invalidate iterators or subranges [29.8.2/1]

  • reduce algorithm: binary_op shall neither invalidate iterators or subranges, nor modify elements in the range [first, last]. [29.8.3/5]

and so on...

missing private key in the distribution certificate on keychain

To add on to others' answers, if you don't have access to that private key anymore it's fairly simple to get back up and running:

  1. revoke your active certificate in the provisioning portal
  2. create new developer certificate (keychain access/.../request for csr...etc.)
  3. download and install a new certificate
  4. create a new provisioning profile for existing app id (on provisioning portal)
  5. download and install new provisioning profile and in the build, settings set the appropriate code signing identities

Android offline documentation and sample codes

This thread is a little old, and I am brand new to this, but I think I found the preferred solution.

First, I assume that you are using Eclipse and the Android ADT plugin.

In Eclipse, choose Window/Android SDK Manager. In the display, expand the entry for the MOST RECENT PLATFORM, even if that is not the platform that your are developing for. As of Jan 2012, it is "Android 4.0.3 (API 15)". When expanded, the first entry is "Documentation for Android SDK" Click the checkbox next to it, and then click the "Install" button.

When done, you should have a new directory in your "android-sdks" called "doc". Look for "offline.html" in there. Since this is packaged with the most recent version, it will document the most recent platform, but it should also show the APIs for previous versions.

How can I maintain fragment state when added to the back stack?

I would suggest a very simple solution.

Take the View reference variable and set view in OnCreateView. Check if view already exists in this variable, then return same view.

   private View fragmentView;

   public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        if (fragmentView != null) {
            return fragmentView;
        }
        View view = inflater.inflate(R.layout.yourfragment, container, false);
        fragmentView = view;
        return view;
    }

jquery $.each() for objects

Basically you need to do two loops here. The one you are doing already is iterating each element in the 0th array element.

You have programs: [ {...}, {...} ] so programs[0] is { "name":"zonealarm", "price":"500" } So your loop is just going over that.

You could do an outer loop over the array

$.each(data.programs, function(index) {

    // then loop over the object elements
    $.each(data.programs[index], function(key, value) {
        console.log(key + ": " + value);
    }

}

python: get directory two levels up

Very easy:

Here is what you want:

import os.path as path

two_up =  path.abspath(path.join(__file__ ,"../.."))

Best way to do Version Control for MS Excel

It depends on what level of integration you want, I've used Subversion/TortoiseSVN which seems fine for simple usage. I have also added in keywords but there seems to be a risk of file corruption. There's an option in Subversion to make the keyword substitutions fixed length and as far as I understand it will work if the fixed length is even but not odd. In any case you don't get any useful sort of diff functionality, I think there are commercial products that will do 'diff'. I did find something that did diff based on converting stuff to plain text and comparing that, but it wasn't very nice.

Query to select data between two dates with the format m/d/yyyy

By default Mysql store and return ‘date’ data type values in “YYYY/MM/DD” format. So if we want to display date in different format then we have to format date values as per our requirement in scripting language

And by the way what is the column data type and in which format you are storing the value.

Drawable-hdpi, Drawable-mdpi, Drawable-ldpi Android

I got one good solution. Here I have attached it as the image below. So try it. It may be helpful to you...!

Enter image description here

How to quickly clear a JavaScript Object?

Something new to think about looking forward to Object.observe in ES7 and with data-binding in general. Consider:

var foo={
   name: "hello"
};

Object.observe(foo, function(){alert('modified');}); // bind to foo

foo={}; // You are no longer bound to foo but to an orphaned version of it
foo.name="there"; // This change will be missed by Object.observe()

So under that circumstance #2 can be the best choice.

How do I add a tool tip to a span element?

Here's the simple, built-in way:

<span title="My tip">text</span>

That gives you plain text tooltips. If you want rich tooltips, with formatted HTML in them, you'll need to use a library to do that. Fortunately there are loads of those.

selenium get current url after loading a page

Page 2 is in a new tab/window ? If it's this, use the code bellow :

try {

    String winHandleBefore = driver.getWindowHandle();

    for(String winHandle : driver.getWindowHandles()){
        driver.switchTo().window(winHandle);
        String act = driver.getCurrentUrl();
    }
    }catch(Exception e){
   System.out.println("fail");
    }

Sending emails with Javascript

If this is just going to open up the user's client to send the email, why not let them compose it there as well. You lose the ability to track what they are sending, but if that's not important, then just collect the addresses and subject and pop up the client to let the user fill in the body.

How do I implement Toastr JS?

Add CDN Files of toastr.css and toastr.js

<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/css/toastr.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/js/toastr.js"></script>

function toasterOptions() {
    toastr.options = {
        "closeButton": false,
        "debug": false,
        "newestOnTop": false,
        "progressBar": true,
        "positionClass": "toast-top-center",
        "preventDuplicates": true,
        "onclick": null,
        "showDuration": "100",
        "hideDuration": "1000",
        "timeOut": "5000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "show",
        "hideMethod": "hide"
    };
};


toasterOptions();
toastr.error("Error Message from toastr");

What does the 'export' command do?

In simple terms, environment variables are set when you open a new shell session. At any time if you change any of the variable values, the shell has no way of picking that change. that means the changes you made become effective in new shell sessions. The export command, on the other hand, provides the ability to update the current shell session about the change you made to the exported variable. You don't have to wait until new shell session to use the value of the variable you changed.

python global name 'self' is not defined

It should be something like:

class Person:
   def setavalue(self, name):         
      self.myname = name      
   def printaname(self):         
      print "Name", self.myname           

def main():
   p = Person()
   p.setavalue("harry")
   p.printaname()  

Batch Script to Run as Administrator

You have a couple options.

  1. If you need to do it using only a batch file and native commands, check out How can I auto-elevate my batch file, so that it requests from UAC admin rights if required?.

  2. If 3rd-party utilities are an option, you can use a tool like Elevate. It is an executable that you call with the program you want to run elevated as a parameter.
    Like this: elevate net share ....

Visual C++ executable and missing MSVCR100d.dll

I got the same error.

I was refering a VS2010 DLL in a VS2012 project.

Just recompiled the DLL on VS2012 and now everything is fine.

Delegates in swift?

Very easy step by step (100% working and tested)

step1: Create method on first view controller

 func updateProcessStatus(isCompleted : Bool){
    if isCompleted{
        self.labelStatus.text = "Process is completed"
    }else{
        self.labelStatus.text = "Process is in progress"
    }
}

step2: Set delegate while push to second view controller

@IBAction func buttonAction(_ sender: Any) {

    let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "secondViewController") as! secondViewController
    secondViewController.delegate = self
    self.navigationController?.pushViewController(secondViewController, animated: true)
}

step3: set delegate like

class ViewController: UIViewController,ProcessStatusDelegate {

step4: Create protocol

protocol ProcessStatusDelegate:NSObjectProtocol{
func updateProcessStatus(isCompleted : Bool)
}

step5: take a variable

var delegate:ProcessStatusDelegate?

step6: While go back to previous view controller call delegate method so first view controller notify with data

@IBAction func buttonActionBack(_ sender: Any) {
    delegate?.updateProcessStatus(isCompleted: true)
    self.navigationController?.popViewController(animated: true)
}

@IBAction func buttonProgress(_ sender: Any) {
    delegate?.updateProcessStatus(isCompleted: false)
    self.navigationController?.popViewController(animated: true)

}

Can you put two conditions in an xslt test attribute?

Not quite, the AND has to be lower-case.

<xsl:when test="4 &lt; 5 and 1 &lt; 2">
<!-- do something -->
</xsl:when>

Programmatically set the initial view controller using Storyboards

You can set Navigation rootviewcontroller as a main view controller. This idea can use for auto login as per application requirement.

UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];

UIViewController viewController = (HomeController*)[mainStoryboard instantiateViewControllerWithIdentifier: @"HomeController"];

UINavigationController navController = [[UINavigationController alloc] initWithRootViewController:viewController];

 self.window.rootViewController = navController;

if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {

    // do stuff for iOS 7 and newer

    navController.navigationBar.barTintColor = [UIColor colorWithRed:88/255.0 green:164/255.0 blue:73/255.0 alpha:1.0];

    navController.navigationItem.leftBarButtonItem.tintColor = [UIColor colorWithRed:88/255.0 green:164/255.0 blue:73/255.0 alpha:1.0];

    navController.navigationBar.tintColor = [UIColor whiteColor];

    navController.navigationItem.titleView.tintColor = [UIColor whiteColor];

    NSDictionary *titleAttributes =@{

                                     NSFontAttributeName :[UIFont fontWithName:@"Helvetica-Bold" size:14.0],

                                     NSForegroundColorAttributeName : [UIColor whiteColor]

                                     };

    navController.navigationBar.titleTextAttributes = titleAttributes;

    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

}

else {

    // do stuff for older versions than iOS 7

    navController.navigationBar.tintColor = [UIColor colorWithRed:88/255.0 green:164/255.0 blue:73/255.0 alpha:1.0];



    navController.navigationItem.titleView.tintColor = [UIColor whiteColor];

}

[self.window makeKeyAndVisible];

For StoryboardSegue Users

UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];

// Go to Login Screen of story board with Identifier name : LoginViewController_Identifier

LoginViewController *loginViewController = (LoginViewController*)[mainStoryboard instantiateViewControllerWithIdentifier:@“LoginViewController_Identifier”];

navigationController = [[UINavigationController alloc] initWithRootViewController:testViewController];

self.window.rootViewController = navigationController;

[self.window makeKeyAndVisible];

// Go To Main screen if you are already Logged In Just check your saving credential here

if([SavedpreferenceForLogin] > 0){
    [loginViewController performSegueWithIdentifier:@"mainview_action" sender:nil];
}

Thanks

How can I discard remote changes and mark a file as "resolved"?

Make sure of the conflict origin: if it is the result of a git merge, see Brian Campbell's answer.

But if is the result of a git rebase, in order to discard remote (their) changes and use local changes, you would have to do a:

git checkout --theirs -- .

See "Why is the meaning of “ours” and “theirs” reversed"" to see how ours and theirs are swapped during a rebase (because the upstream branch is checked out).

assignment operator overloading in c++

#include<iostream>

using namespace std;

class employee
{
    int idnum;
    double salary;
    public:
        employee(){}

        employee(int a,int b)
        {
            idnum=a;
            salary=b;
        }

        void dis()
        {
            cout<<"1st emp:"<<endl<<"idnum="<<idnum<<endl<<"salary="<<salary<<endl<<endl;
        }

        void operator=(employee &emp)
        {
            idnum=emp.idnum;
            salary=emp.salary;
        }

        void show()
        {
            cout<<"2nd emp:"<<endl<<"idnum="<<idnum<<endl<<"salary="<<salary<<endl;
        }
};

main()
{
    int a;
    double b;

    cout<<"enter id num and salary"<<endl;
    cin>>a>>b;
    employee e1(a,b);
    e1.dis();
    employee e2;
    e2=e1;
    e2.show();  
}

Fast query runs slow in SSRS

Had the same problem, and fixed it by giving the shared dataset a default parameter and updating that dataset in the reporting server.

How to set time zone of a java.util.Date?

Use DateFormat. For example,

SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
isoFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = isoFormat.parse("2010-05-23T09:01:02");

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

There are two ways you could simplify your work. 1. import Gson library. 2. use Lombok.

Both of them help you create String from object instance. Gson will parse your object, lombok will override your class object toString method.

I put an example about Gson prettyPrint, I create helper class to print object and collection of objects. If you are using lombok, you could mark your class as @ToString and print your object directly.

@Scope(value = "prototype")
@Component
public class DebugPrint<T> {
   public String PrettyPrint(T obj){
      Gson gson = new GsonBuilder().setPrettyPrinting().create();
      return gson.toJson(obj);
   }
   public String PrettyPrint(Collection<T> list){
      Gson gson = new GsonBuilder().setPrettyPrinting().create();
      return list.stream().map(gson::toJson).collect(Collectors.joining(","));
   }

}

How to disable submit button once it has been clicked?

Another solution i´ve used is to move the button instead of disabling it. In that case you don´t have those "disable" problems. Finally what you really want is people not to press twice, if the button is not there they can´t do it.

You may also replace it with another button.

Which TensorFlow and CUDA version combinations are compatible?

if you are coding in jupyter notebook, and want to check which cuda version tf is using, run the follow command directly into jupyter cell:

!conda list cudatoolkit

!conda list cudnn

and to check if the gpu is visible to tf:

tf.test.is_gpu_available(
    cuda_only=False, min_cuda_compute_capability=None
)

VBA - Run Time Error 1004 'Application Defined or Object Defined Error'

Your cells object is not fully qualified. You need to add a DOT before the cells object. For example

With Worksheets("Cable Cards")
    .Range(.Cells(RangeStartRow, RangeStartColumn), _
           .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

Similarly, fully qualify all your Cells object.

Class file has wrong version 52.0, should be 50.0

If you are using javac to compile, and you get this error, then remove all the .class files

rm *.class     # On Unix-based systems

and recompile.

javac fileName.java

How to "EXPIRE" the "HSET" child key in redis?

This is possible in KeyDB which is a Fork of Redis. Because it's a Fork its fully compatible with Redis and works as a drop in replacement.

Just use the EXPIREMEMBER command. It works with sets, hashes, and sorted sets.

EXPIREMEMBER keyname subkey [time]

You can also use TTL and PTTL to see the expiration

TTL keyname subkey

More documentation is available here: https://docs.keydb.dev/docs/commands/#expiremember

Creating a ZIP archive in memory using System.IO.Compression

Working solution for MVC

    public ActionResult Index()
    {
        string fileName = "test.pdf";
        string fileName1 = "test.vsix";
        string fileNameZip = "Export_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".zip";

        byte[] fileBytes = System.IO.File.ReadAllBytes(@"C:\test\test.pdf");
        byte[] fileBytes1 = System.IO.File.ReadAllBytes(@"C:\test\test.vsix");
        byte[] compressedBytes;
        using (var outStream = new MemoryStream())
        {
            using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
            {
                var fileInArchive = archive.CreateEntry(fileName, CompressionLevel.Optimal);
                using (var entryStream = fileInArchive.Open())
                using (var fileToCompressStream = new MemoryStream(fileBytes))
                {
                    fileToCompressStream.CopyTo(entryStream);
                }

                var fileInArchive1 = archive.CreateEntry(fileName1, CompressionLevel.Optimal);
                using (var entryStream = fileInArchive1.Open())
                using (var fileToCompressStream = new MemoryStream(fileBytes1))
                {
                    fileToCompressStream.CopyTo(entryStream);
                }


            }
            compressedBytes = outStream.ToArray();
        }
        return File(compressedBytes, "application/zip", fileNameZip);
    }

java.lang.IllegalAccessError: tried to access method

This happens when accessing a package scoped method of a class that is in the same package but is in a different jar and classloader.

This was my source, but the link is now broken. Following is full text from google cache:

Packages (as in package access) are scoped per ClassLoader.

You state that the parent ClassLoader loads the interface and the child ClassLoader loads the implementation. This won't work because of the ClassLoader-specific nature of package scoping. The interface isn't visible to the implementation class because, even though it's the same package name, they're in different ClassLoaders.

I only skimmed the posts in this thread, but I think you've already discovered that this will work if you declare the interface to be public. It would also work to have both interface and implementation loaded by the same ClassLoader.

Really, if you expect arbitrary folks to implement the interface (which you apparently do if the implementation is being loaded by a different ClassLoader), then you should make the interface public.

The ClassLoader-scoping of package scope (which applies to accessing package methods, variables, etc.) is similar to the general ClassLoader-scoping of class names. For example, I can define two classes, both named com.foo.Bar, with entirely different implementation code if I define them in separate ClassLoaders.

Joel

Pycharm: run only part of my Python file

You can select a code snippet and use right click menu to choose the action "Execute Selection in console".

generate a random number between 1 and 10 in c

You need to seed the random number generator, from man 3 rand

If no seed value is provided, the rand() function is automatically seeded with a value of 1.

and

The srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are repeatable by calling srand() with the same seed value.

e.g.

srand(time(NULL));

Problem in running .net framework 4.0 website on iis 7.0

Depending on the type of application, another thing to check is under the Advanced Settings for the Application Pool make sure "Enable 32-Bit Applications" is set to True.

I'd checked everything in this thread when I had this issue but all had already been setup correctly, I found this was the problem for me.

How to enable zoom controls and pinch zoom in a WebView?

Use these:

webview.getSettings().setBuiltInZoomControls(true);
webview.getSettings().setDisplayZoomControls(false);

How do I fix a Git detached head?

This approach will potentially discard part of the commit history, but it is easier in case the merge of the old master branch and the current status is tricky, or you simply do not mind losing part of the commit history.

To simply keep things as currently are, without merging, turning the current detached HEAD into the master branch:

  1. Manually back up the repository, in case things go unexpectedly wrong.
  2. Commit the last changes you would like to keep.
  3. Create a temporary branch (let's name it detached-head) that will contain the files in their current status:
git checkout -b detached-head
  1. (a) Delete the master branch if you do not need to keep it
git branch -D master
  1. (b) OR rename if you want to keep it
git branch -M master old-master
  1. Rename the temporary branch as the new master branch
git branch -M detached-head master

Credit: adapted from this Medium article by Gary Lai.

Unknown SSL protocol error in connection

This error also comes up with the Server is down. Email from tech support on the issue:

"We experienced an outage where it affected traffic to the website, as well as Mercurial and Git traffic over HTTPS. SSH was unaffected though. Feel free to check this page for more info:

http://status.bitbucket.org/"

So try again later and it could work itself out. Did for me

SQL Server converting varbinary to string

If you want to convert a single VARBINARY value into VARCHAR (STRING) you can do by declaring a variable like this:

DECLARE @var VARBINARY(MAX)
SET @var = 0x21232F297A57A5A743894A0E4A801FC3
SELECT CAST(@var AS VARCHAR(MAX))

If you are trying to select from table column then you can do like this:

SELECT CAST(myBinaryCol AS VARCHAR(MAX))
FROM myTable

WPF Timer Like C# Timer

you can also use

using System.Timers;
using System.Threading;

Display / print all rows of a tibble (tbl_df)

i prefer to physically print my tables instead:

CONNECT_SERVER="https://196.168.1.1/"
CONNECT_API_KEY<-"hpphotosmartP9000:8273827"

data.frame = data.frame(1:1000, 1000:2)

connectServer <- Sys.getenv("CONNECT_SERVER")
apiKey <- Sys.getenv("CONNECT_API_KEY")

install.packages('print2print')

print2print::send2printer(connectServer, apiKey, data.frame)

Length of string in bash

In response to the post starting:

If you want to use this with command line or function arguments...

with the code:

size=${#1}

There might be the case where you just want to check for a zero length argument and have no need to store a variable. I believe you can use this sort of syntax:

if [ -z "$1" ]; then
    #zero length argument 
else
    #non-zero length
fi

See GNU and wooledge for a more complete list of Bash conditional expressions.

How to get File Created Date and Modified Date

Use :

FileInfo fInfo = new FileInfo('FilePath');
var fFirstTime = fInfo.CreationTime;
var fLastTime = fInfo.LastWriteTime;

How often does python flush to a file?

Here is another approach, up to the OP to choose which one he prefers.

When including the code below in the __init__.py file before any other code, messages printed with print and any errors will no longer be logged to Ableton's Log.txt but to separate files on your disk:

import sys

path = "/Users/#username#"

errorLog = open(path + "/stderr.txt", "w", 1)
errorLog.write("---Starting Error Log---\n")
sys.stderr = errorLog
stdoutLog = open(path + "/stdout.txt", "w", 1)
stdoutLog.write("---Starting Standard Out Log---\n")
sys.stdout = stdoutLog

(for Mac, change #username# to the name of your user folder. On Windows the path to your user folder will have a different format)

When you open the files in a text editor that refreshes its content when the file on disk is changed (example for Mac: TextEdit does not but TextWrangler does), you will see the logs being updated in real-time.

Credits: this code was copied mostly from the liveAPI control surface scripts by Nathan Ramella

How to put the legend out of the plot

Short answer: you can use bbox_to_anchor + bbox_extra_artists + bbox_inches='tight'.


Longer answer: You can use bbox_to_anchor to manually specify the location of the legend box, as some other people have pointed out in the answers.

However, the usual issue is that the legend box is cropped, e.g.:

import matplotlib.pyplot as plt

# data 
all_x = [10,20,30]
all_y = [[1,3], [1.5,2.9],[3,2]]

# Plot
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(all_x, all_y)

# Add legend, title and axis labels
lgd = ax.legend( [ 'Lag ' + str(lag) for lag in all_x], loc='center right', bbox_to_anchor=(1.3, 0.5))
ax.set_title('Title')
ax.set_xlabel('x label')
ax.set_ylabel('y label')

fig.savefig('image_output.png', dpi=300, format='png')

enter image description here

In order to prevent the legend box from getting cropped, when you save the figure you can use the parameters bbox_extra_artists and bbox_inches to ask savefig to include cropped elements in the saved image:

fig.savefig('image_output.png', bbox_extra_artists=(lgd,), bbox_inches='tight')

Example (I only changed the last line to add 2 parameters to fig.savefig()):

import matplotlib.pyplot as plt

# data 
all_x = [10,20,30]
all_y = [[1,3], [1.5,2.9],[3,2]]

# Plot
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(all_x, all_y)

# Add legend, title and axis labels
lgd = ax.legend( [ 'Lag ' + str(lag) for lag in all_x], loc='center right', bbox_to_anchor=(1.3, 0.5))
ax.set_title('Title')
ax.set_xlabel('x label')
ax.set_ylabel('y label')    

fig.savefig('image_output.png', dpi=300, format='png', bbox_extra_artists=(lgd,), bbox_inches='tight')

enter image description here

I wish that matplotlib would natively allow outside location for the legend box as Matlab does:

figure
x = 0:.2:12;
plot(x,besselj(1,x),x,besselj(2,x),x,besselj(3,x));
hleg = legend('First','Second','Third',...
              'Location','NorthEastOutside')
% Make the text of the legend italic and color it brown
set(hleg,'FontAngle','italic','TextColor',[.3,.2,.1])

enter image description here

Strange "java.lang.NoClassDefFoundError" in Eclipse

I thought my problem and its solution could help.So i was getting this same error in my eclipse project.In my project i have couple of jar files and the NOCLASSDEFERROR was thrown for a file in the jar file.

My library files were part of a folder name "lib" in my project heirarchy.I changed my folders name to "libs" and voila it worked.

(I looked into the .classpath file and i had key-value pairs,and the entry for my jar file had key named "lib" and hence i thought probably changing from lib could help.)

Android: Vertical alignment for multi line EditText (Text area)

I think you can use layout:weight = 5 instead android:lines = 5 because when you port your app to smaller device - it does it nicely.. well, both attributes will accomplish your job..

Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'"

I am also a Windows user. And I have installed Python 3.7 and when I try to install any package it throws the same error that you are getting.

Try this out. This worked for me.

python -m pip install numpy

And whenever you install new package just write python -m pip install <package_name>

Hope this is helpful.

How to get DATE from DATETIME Column in SQL?

Try this:

SELECT SUM(transaction_amount) FROM TransactionMaster WHERE Card_No ='123' AND CONVERT(VARCHAR(10),GETDATE(),111)

The GETDATE() function returns the current date and time from the SQL Server.

Adding dictionaries together, Python

Please search the site before asking questions next time: how to concatenate two dictionaries to create a new one in Python?

The easiest way to do it is to simply use your example code, but using the items() member of each dictionary. So, the code would be:

dic0 = {'dic0': 0}
dic1 = {'dic1': 1}
dic2 = dict(dic0.items() + dic1.items())

I tested this in IDLE and it works fine. However, the previous question on this topic states that this method is slow and chews up memory. There are several other ways recommended there, so please see that if memory usage is important.

How to prevent errno 32 broken pipe?

This might be because you are using two method for inserting data into database and this cause the site to slow down.

def add_subscriber(request, email=None):
    if request.method == 'POST':
        email = request.POST['email_field']
        e = Subscriber.objects.create(email=email).save()  <==== 
        return HttpResponseRedirect('/')
    else:
        return HttpResponseRedirect('/')

In above function, the error is where arrow is pointing. The correct implementation is below:

def add_subscriber(request, email=None):
    if request.method == 'POST':
        email = request.POST['email_field']
        e = Subscriber.objects.create(email=email)
        return HttpResponseRedirect('/')
    else:
        return HttpResponseRedirect('/')

Best way to center a <div> on a page vertically and horizontally?

If you are looking at the new browsers(IE10+),

then you can make use of transform property to align a div at the center.

<div class="center-block">this is any div</div>

And css for this should be:

.center-block {
  top:50%;
  left: 50%;
  transform: translate3d(-50%,-50%, 0);
  position: absolute;
}

The catch here is that you don't even have to specify the height and width of the div as it takes care by itself.

Also, if you want to position a div at the center of another div, then you can just specify the position of outer div as relative and then this CSS starts working for your div.

How it works:

When you specify left and top at 50%, the div goes at the the bottom right quarter of the page with its top-left end pinned at the center of the page. This is because, the left/top properties(when given in %) are calculated based on height of the outer div(in your case, window).

But transform uses height/width of the element to determine translation, so you div will move left(50% width) and top(50% its height) since they are given in negatives, thus aligning it to the center of the page.

If you have to support older browsers(and sorry including IE9 as well) then the table cell is most popular method to use.

How does cellForRowAtIndexPath work?

I'll try and break it down (example from documention)

/* 
 *   The cellForRowAtIndexPath takes for argument the tableView (so if the same object
 *   is delegate for several tableViews it can identify which one is asking for a cell),
 *   and an indexPath which determines which row and section the cell is returned for. 
 */ 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    /*
     *   This is an important bit, it asks the table view if it has any available cells
     *   already created which it is not using (if they are offScreen), so that it can
     *   reuse them (saving the time of alloc/init/load from xib a new cell ).
     *   The identifier is there to differentiate between different types of cells
     *   (you can display different types of cells in the same table view)
     */

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];

    /*
     *   If the cell is nil it means no cell was available for reuse and that we should
     *   create a new one.
     */
    if (cell == nil) {

        /* 
         *   Actually create a new cell (with an identifier so that it can be dequeued). 
         */

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"] autorelease];

        cell.selectionStyle = UITableViewCellSelectionStyleNone;

    }

    /*
     *   Now that we have a cell we can configure it to display the data corresponding to
     *   this row/section
     */

    NSDictionary *item = (NSDictionary *)[self.content objectAtIndex:indexPath.row];
    cell.textLabel.text = [item objectForKey:@"mainTitleKey"];
    cell.detailTextLabel.text = [item objectForKey:@"secondaryTitleKey"];
    NSString *path = [[NSBundle mainBundle] pathForResource:[item objectForKey:@"imageKey"] ofType:@"png"];
    UIImage *theImage = [UIImage imageWithContentsOfFile:path];
    cell.imageView.image = theImage;

    /* Now that the cell is configured we return it to the table view so that it can display it */

    return cell;

}

This is a DataSource method so it will be called on whichever object has declared itself as the DataSource of the UITableView. It is called when the table view actually needs to display the cell onscreen, based on the number of rows and sections (which you specify in other DataSource methods).

Pylint, PyChecker or PyFlakes?

Well, I am a bit curious, so I just tested the three myself right after asking the question ;-)

Ok, this is not a very serious review, but here is what I can say:

I tried the tools with the default settings (it's important because you can pretty much choose your check rules) on the following script:

#!/usr/local/bin/python
# by Daniel Rosengren modified by e-satis

import sys, time
stdout = sys.stdout

BAILOUT = 16
MAX_ITERATIONS = 1000

class Iterator(object) :

    def __init__(self):

        print 'Rendering...'
        for y in xrange(-39, 39):
            stdout.write('\n')
            for x in xrange(-39, 39):
                if self.mandelbrot(x/40.0, y/40.0) :
                    stdout.write(' ')
                else:
                    stdout.write('*')


    def mandelbrot(self, x, y):
        cr = y - 0.5
        ci = x
        zi = 0.0
        zr = 0.0

        for i in xrange(MAX_ITERATIONS) :
            temp = zr * zi
            zr2 = zr * zr
            zi2 = zi * zi
            zr = zr2 - zi2 + cr
            zi = temp + temp + ci

            if zi2 + zr2 > BAILOUT:
                return i

        return 0

t = time.time()
Iterator()
print '\nPython Elapsed %.02f' % (time.time() - t)

As a result:

  • PyChecker is troublesome because it compiles the module to analyze it. If you don't want your code to run (e.g, it performs a SQL query), that's bad.
  • PyFlakes is supposed to be light. Indeed, it decided that the code was perfect. I am looking for something quite severe so I don't think I'll go for it.
  • PyLint has been very talkative and rated the code 3/10 (OMG, I'm a dirty coder !).

Strong points of PyLint:

  • Very descriptive and accurate report.
  • Detect some code smells. Here it told me to drop my class to write something with functions because the OO approach was useless in this specific case. Something I knew, but never expected a computer to tell me :-p
  • The fully corrected code run faster (no class, no reference binding...).
  • Made by a French team. OK, it's not a plus for everybody, but I like it ;-)

Cons of Pylint:

  • Some rules are really strict. I know that you can change it and that the default is to match PEP8, but is it such a crime to write 'for x in seq'? Apparently yes because you can't write a variable name with less than 3 letters. I will change that.
  • Very very talkative. Be ready to use your eyes.

Corrected script (with lazy doc strings and variable names):

#!/usr/local/bin/python
# by Daniel Rosengren, modified by e-satis
"""
Module doctring
"""


import time
from sys import stdout

BAILOUT = 16
MAX_ITERATIONS = 1000

def mandelbrot(dim_1, dim_2):
    """
    function doc string
    """
    cr1 = dim_1 - 0.5
    ci1 = dim_2
    zi1 = 0.0
    zr1 = 0.0

    for i in xrange(MAX_ITERATIONS) :
        temp = zr1 * zi1
        zr2 = zr1 * zr1
        zi2 = zi1 * zi1
        zr1 = zr2 - zi2 + cr1
        zi1 = temp + temp + ci1

        if zi2 + zr2 > BAILOUT:
            return i

    return 0

def execute() :
    """
    func doc string
    """
    print 'Rendering...'
    for dim_1 in xrange(-39, 39):
        stdout.write('\n')
        for dim_2 in xrange(-39, 39):
            if mandelbrot(dim_1/40.0, dim_2/40.0) :
                stdout.write(' ')
            else:
                stdout.write('*')


START_TIME = time.time()
execute()
print '\nPython Elapsed %.02f' % (time.time() - START_TIME)

Thanks to Rudiger Wolf, I discovered pep8 that does exactly what its name suggests: matching PEP8. It has found several syntax no-nos that Pylint did not. But Pylint found stuff that was not specifically linked to PEP8 but interesting. Both tools are interesting and complementary.

Eventually I will use both since there are really easy to install (via packages or setuptools) and the output text is so easy to chain.

To give you a little idea of their output:

pep8:

./python_mandelbrot.py:4:11: E401 multiple imports on one line
./python_mandelbrot.py:10:1: E302 expected 2 blank lines, found 1
./python_mandelbrot.py:10:23: E203 whitespace before ':'
./python_mandelbrot.py:15:80: E501 line too long (108 characters)
./python_mandelbrot.py:23:1: W291 trailing whitespace
./python_mandelbrot.py:41:5: E301 expected 1 blank line, found 3

Pylint:

************* Module python_mandelbrot
C: 15: Line too long (108/80)
C: 61: Line too long (85/80)
C:  1: Missing docstring
C:  5: Invalid name "stdout" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
C: 10:Iterator: Missing docstring
C: 15:Iterator.__init__: Invalid name "y" (should match [a-z_][a-z0-9_]{2,30}$)
C: 17:Iterator.__init__: Invalid name "x" (should match [a-z_][a-z0-9_]{2,30}$)

[...] and a very long report with useful stats like :

Duplication
-----------

+-------------------------+------+---------+-----------+
|                         |now   |previous |difference |
+=========================+======+=========+===========+
|nb duplicated lines      |0     |0        |=          |
+-------------------------+------+---------+-----------+
|percent duplicated lines |0.000 |0.000    |=          |
+-------------------------+------+---------+-----------+

Using the "With Clause" SQL Server 2008

Try the sp_foreachdb procedure.

window.location.href doesn't redirect

Some parenthesis are missing.

Change

 window.location.href = "/comments.aspx?id=" + movieShareId.textContent || movieShareId.innerText + "/";

to

 window.location = "/comments.aspx?id=" + (movieShareId.textContent || movieShareId.innerText) + "/";

No priority is given to the || compared to the +.

Remove also everything after the window.location assignation : this code isn't supposed to be executed as the page changes.

Note: you don't need to set location.href. It's enough to just set location.

How to send email via Django?

You need to use smtp as backend in settings.py

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

If you use backend as console, you will receive output in console

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

And also below settings in addition

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'password'

If you are using gmail for this, setup 2-step verification and Application specific password and copy and paste that password in above EMAIL_HOST_PASSWORD value.

Node.js request CERT_HAS_EXPIRED

Here is a more concise way to achieve the "less insecure" method proposed by CoolAJ86

request({
  url: url,
  agentOptions: {
    rejectUnauthorized: false
  }
}, function (err, resp, body) {
  // ...
});

'if' in prolog?

A standard prolog predicate will do this.

   isfive(5). 

will evaluate to true if you call it with 5 and fail(return false) if you run it with anything else. For not equal you use \=

isNotEqual(A,B):- A\=B.

Technically it is does not unify, but it is similar to not equal.

Learn Prolog Now is a good website for learning prolog.

Edit: To add another example.

isEqual(A,A). 

How to embed a .mov file in HTML?

<object CLASSID="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="320" height="256" CODEBASE="http://www.apple.com/qtactivex/qtplugin.cab">
    <param name="src" value="sample.mov">
    <param name="qtsrc" value="rtsp://realmedia.uic.edu/itl/ecampb5/demo_broad.mov">
    <param name="autoplay" value="true">
    <param name="loop" value="false">
    <param name="controller" value="true">
    <embed src="sample.mov" qtsrc="rtsp://realmedia.uic.edu/itl/ecampb5/demo_broad.mov" width="320" height="256" autoplay="true" loop="false" controller="true" pluginspage="http://www.apple.com/quicktime/"></embed>
</object>

source is the first search result of the Google

error: command 'gcc' failed with exit status 1 while installing eventlet

For Fedora:

sudo yum install python-devel

sudo yum install libevent-devel

and finally:

sudo easy_install gevent

String vs. StringBuilder

Yes, StringBuilder gives better performance while performing repeated operation over a string. It is because all the changes are made to a single instance so it can save a lot of time instead of creating a new instance like String.

String Vs Stringbuilder

  • String

    1. under System namespace
    2. immutable (read-only) instance
    3. performance degrades when continuous change of value occures
    4. thread safe
  • StringBuilder (mutable string)

    1. under System.Text namespace
    2. mutable instance
    3. shows better performance since new changes are made to existing instance

Strongly recommend dotnet mob article : String Vs StringBuilder in C#.

Related Stack Overflow question: Mutability of string when string doesn't change in C#?.

Access denied for user 'root'@'localhost' (using password: YES) (Mysql::Error)

try using root like..

mysql -uroot

then you can check different user and host after you logged in by using

select user,host,password from mysql.user;

FULL OUTER JOIN vs. FULL JOIN

Microsoft® SQL Server™ 2000 uses these SQL-92 keywords for outer joins specified in a FROM clause:

  • LEFT OUTER JOIN or LEFT JOIN

  • RIGHT OUTER JOIN or RIGHT JOIN

  • FULL OUTER JOIN or FULL JOIN

From MSDN

The full outer join or full join returns all rows from both tables, matching up the rows wherever a match can be made and placing NULLs in the places where no matching row exists.

changing source on html5 video tag

Using JavaScript and jQuery:

<script src="js/jquery.js"></script>
...
<video id="vid" width="1280" height="720" src="v/myvideo01.mp4" controls autoplay></video>
...
function chVid(vid) {
    $("#vid").attr("src",vid);
}
...
<div onclick="chVid('v/myvideo02.mp4')">See my video #2!</div>

Reload the page after ajax success

You use the ajaxStop to execute code when the ajax are completed:

$(document).ajaxStop(function(){
  setTimeout("window.location = 'otherpage.html'",100);
});

What is the difference between "long", "long long", "long int", and "long long int" in C++?

This looks confusing because you are taking long as a datatype itself.

long is nothing but just the shorthand for long int when you are using it alone.

long is a modifier, you can use it with double also as long double.

long == long int.

Both of them take 4 bytes.

What is the default maximum heap size for Sun's JVM from Java SE 6?

To answer this question it's critical whether the Java VM is in CLIENT or SERVER mode. You can specify "-client" or "-server" options. Otherwise java uses internal rules; basically win32 is always client and Linux is always server, but see the table here:

http://docs.oracle.com/javase/6/docs/technotes/guides/vm/server-class.html

Sun/Oracle jre6u18 doc says re client: the VM gets 1/2 of physical memory if machine has <= 192MB; 1/4 of memory if machine has <= 1Gb; max 256Mb. In my test on a 32bit WindowsXP system with 2Gb phys mem, Java allocated 256Mb, which agrees with the doc.

Sun/Oracle jre6u18 doc says re server: same as client, then adds confusing language: for 32bit JVM the default max is 1Gb, and for 64 bit JVM the default is 32Gb. In my test on a 64bit linux machine with 8Gb physical, Java allocates 2Gb, which is 1/4 of physical; on a 64bit linux machine with 128Gb physical Java allocates 32Gb, again 1/4 of physical.

Thanks to this SO post for guiding me:

Definition of server-class machine changed recently?

Python socket.error: [Errno 111] Connection refused

The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND command on another connection, but it apparently was "not opening [it] up in sync with the client side".

Well, the main reason would be there was no synchronisation whatsoever. Calling:

cs.send("SEND " + FILE)
cs.close()

would just place the data into a OS buffer; close would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep after close might mitigate the problem, but this is not synchronisation.

The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK, or better PORT 36250 to indicate where to connect). This would make sure the server is already listening.

The other thing is you must check the return values of send to make sure how many bytes was taken from your buffer. Or use sendall.

(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)

Generate a heatmap in MatPlotLib using a scatter data set

If you don't want hexagons, you can use numpy's histogram2d function:

import numpy as np
import numpy.random
import matplotlib.pyplot as plt

# Generate some test data
x = np.random.randn(8873)
y = np.random.randn(8873)

heatmap, xedges, yedges = np.histogram2d(x, y, bins=50)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

plt.clf()
plt.imshow(heatmap.T, extent=extent, origin='lower')
plt.show()

This makes a 50x50 heatmap. If you want, say, 512x384, you can put bins=(512, 384) in the call to histogram2d.

Example: Matplotlib heat map example

What does cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);

When the normType is NORM_MINMAX, cv::normalize normalizes _src in such a way that the min value of dst is alpha and max value of dst is beta. cv::normalize does its magic using only scales and shifts (i.e. adding constants and multiplying by constants).

CV_8UC1 says how many channels dst has.

The documentation here is pretty clear: http://docs.opencv.org/modules/core/doc/operations_on_arrays.html#normalize

Maven Modules + Building a Single Specific Module

Say Parent pom.xml contains 6 modules and you want to run A, B and F.

<modules>
        <module>A</module>
        <module>B</module>
        <module>C</module>
        <module>D</module>
        <module>E</module>
        <module>F</module>
  </modules>

1- cd into parent project

 mvn --projects A,B,F --also-make clean install

OR

mvn -pl A,B,F -am clean install

OR

mvn -pl A,B,F -amd clean install

Note: When you specify a project with the -am option, Maven will build all of the projects that the specified project depends upon (either directly or indirectly). Maven will examine the list of projects and walk down the dependency tree, finding all of the projects that it needs to build.

While the -am command makes all of the projects required by a particular project in a multi-module build, the -amd or --also-make-dependents option configures Maven to build a project and any project that depends on that project. When using --also-make-dependents, Maven will examine all of the projects in our reactor to find projects that depend on a particular project. It will automatically build those projects and nothing else.

How do I view cookies in Internet Explorer 11 using Developer Tools

Not quite an answer (not “using Developer Tools”), but there is a third-party tool for it: IECookiesView from NirSoft. Hope this helps someone.

screenshot

image taken from Softpedia

Android Transparent TextView?

To set programmatically:

setBackgroundColor(Color.TRANSPARENT);

For me, I also had to set it to Color.TRANSPARENT on the parent layout.

Alter MySQL table to add comments on columns

The information schema isn't the place to treat these things (see DDL database commands).

When you add a comment you need to change the table structure (table comments).

From MySQL 5.6 documentation:

INFORMATION_SCHEMA is a database within each MySQL instance, the place that stores information about all the other databases that the MySQL server maintains. The INFORMATION_SCHEMA database contains several read-only tables. They are actually views, not base tables, so there are no files associated with them, and you cannot set triggers on them. Also, there is no database directory with that name.

Although you can select INFORMATION_SCHEMA as the default database with a USE statement, you can only read the contents of tables, not perform INSERT, UPDATE, or DELETE operations on them.

Chapter 21 INFORMATION_SCHEMA Tables

Possible to perform cross-database queries with PostgreSQL?

see https://www.cybertec-postgresql.com/en/joining-data-from-multiple-postgres-databases/ [published 2017]

These days you also have the option to use https://prestodb.io/

You can run SQL on that PrestoDB node and it will distribute the SQL query as required. It can connect to the same node twice for different databases, or it might be connecting to different nodes on different hosts.

It does not support:

DELETE
ALTER TABLE
CREATE TABLE (CREATE TABLE AS is supported)
GRANT
REVOKE
SHOW GRANTS
SHOW ROLES
SHOW ROLE GRANTS

So you should only use it for SELECT and JOIN needs. Connect directly to each database for the above needs. (It looks like you can also INSERT or UPDATE which is nice)

Client applications connect to PrestoDB primarily using JDBC, but other types of connection are possible including a Tableu compatible web API

This is an open source tool governed by the Linux Foundation and Presto Foundation.

The founding members of the Presto Foundation are: Facebook, Uber, Twitter, and Alibaba.

The current members are: Facebook, Uber, Twitter, Alibaba, Alluxio, Ahana, Upsolver, and Intel.

What do Push and Pop mean for Stacks?

after all these good examples adam shankman still can't make sense of it. I think you should open up some code and try it. The second you try a myStack.Push(1) and myStack.Pop(1) you really should get the picture. But by the looks of it, even that will be a challenge for you!

To get total number of columns in a table in sql

This query gets the columns name

SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = 'YourTableName'

And this one gets the count

SELECT Count(*) FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = 'YourTableName'

How to open a website when a Button is clicked in Android application?

Import import android.net.Uri;

Intent openURL = new Intent(android.content.Intent.ACTION_VIEW);
openURL.setData(Uri.parse("http://www.example.com"));
startActivity(openURL);

or it can be done using,

TextView textView = (TextView)findViewById(R.id.yourID);

textView.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_BROWSABLE);
        intent.setData(Uri.parse("http://www.typeyourURL.com"));
        startActivity(intent);
    } });

How to insert a new key value pair in array in php?

To add:

$arr["key"] = "value";

Then simply return $arr

Can't return directly like this way return $arr["key"] = "value";

Cause of No suitable driver found for

Can you import the driver (org.hsqldb.jdbcDriver) into one of your source files? (To test that the class is actually on your class path).

If you can't import it then you could try including hsqldb.jar in your build path.

How to get Selected Text from select2 when using <input>

Again I suggest Simple and Easy

Its Working Perfect with ajax when user search and select it saves the selected information via ajax

 $("#vendor-brands").select2({
   ajax: {
   url:site_url('general/get_brand_ajax_json'),
  dataType: 'json',
  delay: 250,
  data: function (params) {
  return {
    q: params.term, // search term
    page: params.page
  };
},
processResults: function (data, params) {
  // parse the results into the format expected by Select2
  // since we are using custom formatting functions we do not need to
  // alter the remote JSON data, except to indicate that infinite
  // scrolling can be used
  params.page = params.page || 1;

  return {
    results: data,
    pagination: {
      more: (params.page * 30) < data.total_count
    }
  };
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom    formatter work
minimumInputLength: 1,
}).on("change", function(e) {


  var lastValue = $("#vendor-brands option:last-child").val();
  var lastText = $("#vendor-brands option:last-child").text();

  alert(lastValue+' '+lastText);
 });

Putting an if-elif-else statement on one line?

MESSAGELENGHT = 39
"A normal function call using if elif and else."
if MESSAGELENGHT == 16:
    Datapacket = "word"
elif MESSAGELENGHT == 8:
     Datapacket = 'byte'
else:
     Datapacket = 'bit'

#similarly for a oneliner expresion:
    

Datapacket = "word" if MESSAGELENGHT == 16 else 'byte' if MESSAGELENGHT == 8 else 'bit'
print(Datapacket)

Thanks

PowerShell Remoting giving "Access is Denied" error

Had similar problems recently. Would suggest you carefully check if the user you're connecting with has proper authorizations on the remote machine.

You can review permissions using the following command.

Set-PSSessionConfiguration -ShowSecurityDescriptorUI -Name Microsoft.PowerShell

Found this tip here (updated link, thanks "unbob"):

https://devblogs.microsoft.com/scripting/configure-remote-security-settings-for-windows-powershell/

It fixed it for me.

How to find out which package version is loaded in R?

You can use sessionInfo() to accomplish that.

> sessionInfo()
R version 2.15.0 (2012-03-30)
Platform: x86_64-pc-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8    LC_PAPER=C                 LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C             LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] graphics  grDevices utils     datasets  stats     grid      methods   base     

other attached packages:
[1] ggplot2_0.9.0  reshape2_1.2.1 plyr_1.7.1    

loaded via a namespace (and not attached):
 [1] colorspace_1.1-1   dichromat_1.2-4    digest_0.5.2       MASS_7.3-18        memoise_0.1        munsell_0.3       
 [7] proto_0.3-9.2      RColorBrewer_1.0-5 scales_0.2.0       stringr_0.6       
> 

However, as per comments and the answer below, there are better options

> packageVersion("snow")

[1] ‘0.3.9’

Or:

"Rmpi" %in% loadedNamespaces()

What's a good, free serial port monitor for reverse-engineering?

Portmon from sysinternals (now MSFT) is probably the best monitor.

I haven't found a good free tool that will emulate a port and record/replay comms. The commercial ones were expensive and either so limited or so complex if you want to respond to commands that I ended up using expect and python on a second machine.

Location Services not working in iOS 8

The old code for asking location won't work in iOS 8. You can try this method for location authorization:

- (void)requestAlwaysAuthorization
{
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];

    // If the status is denied or only granted for when in use, display an alert
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status ==        kCLAuthorizationStatusDenied) {
        NSString *title;
        title = (status == kCLAuthorizationStatusDenied) ? @"Location services are off" :   @"Background location is not enabled";
        NSString *message = @"To use background location you must turn on 'Always' in the Location Services Settings";

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
                                                            message:message
                                                           delegate:self
                                                  cancelButtonTitle:@"Cancel"
                                                  otherButtonTitles:@"Settings", nil];
        [alertView show];
    }
    // The user has not enabled any location services. Request background authorization.
    else if (status == kCLAuthorizationStatusNotDetermined) {
        [self.locationManager requestAlwaysAuthorization];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        // Send the user to the Settings for this app
        NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:settingsURL];
    }
}

"Unable to get the VLookup property of the WorksheetFunction Class" error

I was having the same problem. It seems that passing Me.ComboBox1.Value as an argument for the Vlookup function is causing the issue. What I did was assign this value to a double and then put it into the Vlookup function.

Dim x As Double
x = Me.ComboBox1.Value
Me.TextBox1.Value = Application.WorksheetFunction.VLookup(x, Worksheets("Sheet3").Range("Names"), 2, False) 

Or, for a shorter method, you can just convert the type within the Vlookup function using Cdbl(<Value>).

So it would end up being

Me.TextBox1.Value = Application.WorksheetFunction.VLookup(Cdbl(Me.ComboBox1.Value), Worksheets("Sheet3").Range("Names"), 2, False) 

Strange as it may sound, it works for me.

Hope this helps.

mongodb how to get max value from collections

For max value, we can write sql query as

select age from table_name order by age desc limit 1

same way we can write in mongodb too.

db.getCollection('collection_name').find().sort({"age" : -1}).limit(1); //max age
db.getCollection('collection_name').find().sort({"age" : 1}).limit(1); //min age

How do I delete multiple rows in Entity Framework (without foreach)

context.Widgets.RemoveRange(context.Widgets.Where(w => w.WidgetId == widgetId).ToList()); db.SaveChanges();

Check if a String contains numbers Java

s=s.replaceAll("[*a-zA-Z]", "") replaces all alphabets

s=s.replaceAll("[*0-9]", "") replaces all numerics

if you do above two replaces you will get all special charactered string

If you want to extract only integers from a String s=s.replaceAll("[^0-9]", "")

If you want to extract only Alphabets from a String s=s.replaceAll("[^a-zA-Z]", "")

Happy coding :)

What I can do to resolve "1 commit behind master"?

If the branch is behind master, then delete the remote branch. Then go to local branch and run :

git pull origin master --rebase

Then, again push the branch to origin:

git push -u origin <branch-name>

BeautifulSoup Grab Visible Webpage Text

from bs4 import BeautifulSoup
from bs4.element import Comment
import urllib.request
import re
import ssl

def tag_visible(element):
    if element.parent.name in ['style', 'script', 'head', 'title', 'meta', '[document]']:
        return False
    if isinstance(element, Comment):
        return False
    if re.match(r"[\n]+",str(element)): return False
    return True
def text_from_html(url):
    body = urllib.request.urlopen(url,context=ssl._create_unverified_context()).read()
    soup = BeautifulSoup(body ,"lxml")
    texts = soup.findAll(text=True)
    visible_texts = filter(tag_visible, texts)  
    text = u",".join(t.strip() for t in visible_texts)
    text = text.lstrip().rstrip()
    text = text.split(',')
    clean_text = ''
    for sen in text:
        if sen:
            sen = sen.rstrip().lstrip()
            clean_text += sen+','
    return clean_text
url = 'http://www.nytimes.com/2009/12/21/us/21storm.html'
print(text_from_html(url))

Android Percentage Layout Height

Just as you said, I'd recommend weights. Percentages would be incredibly useful (don't know why they aren't supported), but one way you could do it is like so:

<LinearLayout
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    >
    <LinearLayout
        android:layout_height="0dp"
        android:layout_width="fill_parent"
        android:layout_weight="1"
        >
    </LinearLayout>
    <View
        android:layout_height="0dp"
        android:layout_width="fill_parent"
        android:layout_weight="1"
    />
</LinearLayout>

The takeaway being that you have an empty View that will take up the remaining space. Not ideal, but it does what you're looking for.

MySQL joins and COUNT(*) from another table

SELECT DISTINCT groups.id, 
       (SELECT COUNT(*) FROM group_members
        WHERE member_id = groups.id) AS memberCount
FROM groups

if else statement in AngularJS templates

ng If else statement

ng-if="receiptData.cart == undefined ? close(): '' ;"

JSON and escaping characters

This is not a bug in either implementation. There is no requirement to escape U+00B0. To quote the RFC:

2.5. Strings

The representation of strings is similar to conventions used in the C family of programming languages. A string begins and ends with quotation marks. All Unicode characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F).

Any character may be escaped.

Escaping everything inflates the size of the data (all code points can be represented in four or fewer bytes in all Unicode transformation formats; whereas encoding them all makes them six or twelve bytes).

It is more likely that you have a text transcoding bug somewhere in your code and escaping everything in the ASCII subset masks the problem. It is a requirement of the JSON spec that all data use a Unicode encoding.

How to select all the columns of a table except one column?

Without creating new table you can do simply (e.g with mysqli):

  1. get all columns
  2. loop through all columns and remove wich you want
  3. make your query

$r = mysqli_query('SELECT column_name FROM information_schema.columns WHERE table_name = table_to_query');

$c = count($r); while($c--) if($r[$c]['column_name'] != 'column_to_remove_from_query') $a[] = $r[$c]['column_name']; else unset($r[$c]);

$r = mysqli_query('SELECT ' . implode(',', $a) . ' FROM table_to_query');

Is there a Social Security Number reserved for testing/examples?

There are multiple number groups and some particular numbers that will never be allocated:

Consider using one of these (the obviously invalid 000-00-0000 would be a good one IMO).

(Answer has been updated to provide source information beyond Wikipedia and remove information that is no longer accurate after the SSA made its randomization change in mid 2011.)

How to keep form values after post

you can save them into a $_SESSION variable and then when the user calls that page again populate all the inputs with their respective session variables.

ActionBarActivity cannot resolve a symbol

Make sure that in the path to the project there is no foldername having whitespace. While creating a project the specified path folders must not contain any space in their naming.

How to force child div to be 100% of parent div's height without specifying parent's height?

The easiest way to do this is to just fake it. A List Apart has covered this extensively over the years, like in this article from Dan Cederholm from 2004.

Here's how I usually do it:

<div id="container" class="clearfix" style="margin:0 auto;width:950px;background:white url(SOME_REPEATING_PATTERN.png) scroll repeat-y center top;">
    <div id="navigation" style="float:left;width:190px;padding-right:10px;">
        <!-- Navigation -->
    </div>
    <div id="content" style="float:left;width:750px;">
        <!-- Content -->
    </div>
</div>

You can easily add a header onto this design by wrapping #container in another div, embedding the header div as #container's sibling, and moving the margin and width styles to the parent container. Also, the CSS should be moved into a separate file and not kept inline, etc. etc. Finally, the clearfix class can be found on positioniseverything.

SQL use CASE statement in WHERE IN clause

 select  * from Tran_LibraryBooksTrans LBT  left join
 Tran_LibraryIssuedBooks LIB ON   case WHEN LBT.IssuedTo='SN' AND
 LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1 when LBT.IssuedTo='SM'
 AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1 WHEN
 LBT.IssuedTo='BO' AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1
 ELSE 0 END`enter code here`select  * from Tran_LibraryBooksTrans LBT 
 left join Tran_LibraryIssuedBooks LIB ON   case WHEN LBT.IssuedTo='SN'
 AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1 when
 LBT.IssuedTo='SM' AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1
 WHEN LBT.IssuedTo='BO' AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN
 1 ELSE 0 END

How to implement class constants?

TypeScript 2.0 has the readonly modifier:

class MyClass {
    readonly myReadOnlyProperty = 1;

    myMethod() {
        console.log(this.myReadOnlyProperty);
        this.myReadOnlyProperty = 5; // error, readonly
    }
}

new MyClass().myReadOnlyProperty = 5; // error, readonly

It's not exactly a constant because it allows assignment in the constructor, but that's most likely not a big deal.

Alternative Solution

An alternative is to use the static keyword with readonly:

class MyClass {
    static readonly myReadOnlyProperty = 1;

    constructor() {
        MyClass.myReadOnlyProperty = 5; // error, readonly
    }

    myMethod() {
        console.log(MyClass.myReadOnlyProperty);
        MyClass.myReadOnlyProperty = 5; // error, readonly
    }
}

MyClass.myReadOnlyProperty = 5; // error, readonly

This has the benefit of not being assignable in the constructor and only existing in one place.

How do you connect to a MySQL database using Oracle SQL Developer?

Under Tools > Preferences > Databases there is a third party JDBC driver path that must be setup. Once the driver path is setup a separate 'MySQL' tab should appear on the New Connections dialog.

Note: This is the same jdbc connector that is available as a JAR download from the MySQL website.

Is there any way to wait for AJAX response and halt execution?

The simple answer is to turn off async. But that's the wrong thing to do. The correct answer is to re-think how you write the rest of your code.

Instead of writing this:

function functABC(){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        success: function(data) {
            return data;
        }
    });
}

function foo () {
    var response = functABC();
    some_result = bar(response);
    // and other stuff and
    return some_result;
}

You should write it like this:

function functABC(callback){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        success: callback
    });
}

function foo (callback) {
    functABC(function(data){
        var response = data;
        some_result = bar(response);
        // and other stuff and
        callback(some_result);
    })
}

That is, instead of returning result, pass in code of what needs to be done as callbacks. As I've shown, callbacks can be nested to as many levels as you have function calls.


A quick explanation of why I say it's wrong to turn off async:

Turning off async will freeze the browser while waiting for the ajax call. The user cannot click on anything, cannot scroll and in the worst case, if the user is low on memory, sometimes when the user drags the window off the screen and drags it in again he will see empty spaces because the browser is frozen and cannot redraw. For single threaded browsers like IE7 it's even worse: all websites freeze! Users who experience this may think you site is buggy. If you really don't want to do it asynchronously then just do your processing in the back end and refresh the whole page. It would at least feel not buggy.

Install shows error in console: INSTALL FAILED CONFLICTING PROVIDER

I thought uninstalling the app by dragging its icon to "Uninstall" would solve the problem, but it did not.

Here is what solved the problem:

  1. Go to Settings
  2. Choose Apps
  3. Find your app (yes I was surprised to still find it here!) and press it
  4. In the top-right, press the 3 dots
  5. Select "Uninstall for all users"

Try again, it should work now.

String.Replace(char, char) method in C#

Here is your exact answer...

const char LineFeed = '\n'; // #10
string temp = new System.Text.RegularExpressions.Regex(
                  LineFeed
              ).Replace(mystring, string.Empty);

But this one is much better... Specially if you are trying to split the lines (you may also use it with Split)

const char CarriageReturn = '\r'; // #13
const char LineFeed = '\n'; // #10
string temp = new System.Text.RegularExpressions.Regex(
                  string.Format("{0}?{1}", CarriageReturn, LineFeed)
              ).Replace(mystring, string.Empty);

Update my gradle dependencies in eclipse

I tried all above options but was still getting error, in my case issue was I have not setup gradle installation directory in eclipse, following worked:

eclipse -> Window -> Preferences -> Gradle -> "Select Local Installation Directory"

Click on Browse button and provide path.

Even though question is answered, thought to share in case somebody else is facing similar issue.

Cheers !

How do I print out the contents of a vector?

How about for_each + lambda expression:

#include <vector>
#include <algorithm>
// ...
std::vector<char> vec;
// ...
std::for_each(
              vec.cbegin(),
              vec.cend(),
              [] (const char c) {std::cout << c << " ";} 
              );
// ...

Of course, a range-based for is the most elegant solution for this concrete task, but this one gives many other possibilities as well.

Explanation

The for_each algorithm takes an input range and a callable object, calling this object on every element of the range. An input range is defined by two iterators. A callable object can be a function, a pointer to function, an object of a class which overloads () operator or as in this case, a lambda expression. The parameter for this expression matches the type of the elements from vector.

The beauty of this implementation is the power you get from lambda expressions - you can use this approach for a lot more things than just printing the vector.

Java - Writing strings to a CSV file

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class CsvFile {

    public static void main(String[]args){
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(new File("NewData.csv"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        StringBuilder builder = new StringBuilder();
        String columnNamesList = "Id,Name";
        // No need give the headers Like: id, Name on builder.append
        builder.append(columnNamesList +"\n");
        builder.append("1"+",");
        builder.append("Chola");
        builder.append('\n');
        pw.write(builder.toString());
        pw.close();
        System.out.println("done!");
    }
}

What is a Y-combinator?

As a newbie to combinators, I found Mike Vanier's article (thanks Nicholas Mancuso) to be really helpful. I would like to write a summary, besides documenting my understanding, if it could be of help to some others I would be very glad.

From Crappy to Less Crappy

Using factorial as an example, we use the following almost-factorial function to calculate factorial of number x:

def almost-factorial f x = if iszero x
                           then 1
                           else * x (f (- x 1))

In the pseudo-code above, almost-factorial takes in function f and number x (almost-factorial is curried, so it can be seen as taking in function f and returning a 1-arity function).

When almost-factorial calculates factorial for x, it delegates the calculation of factorial for x - 1 to function f and accumulates that result with x (in this case, it multiplies the result of (x - 1) with x).

It can be seen as almost-factorial takes in a crappy version of factorial function (which can only calculate till number x - 1) and returns a less-crappy version of factorial (which calculates till number x). As in this form:

almost-factorial crappy-f = less-crappy-f

If we repeatedly pass the less-crappy version of factorial to almost-factorial, we will eventually get our desired factorial function f. Where it can be considered as:

almost-factorial f = f

Fix-point

The fact that almost-factorial f = f means f is the fix-point of function almost-factorial.

This was a really interesting way of seeing the relationships of the functions above and it was an aha moment for me. (please read Mike's post on fix-point if you haven't)

Three functions

To generalize, we have a non-recursive function fn (like our almost-factorial), we have its fix-point function fr (like our f), then what Y does is when you give Y fn, Y returns the fix-point function of fn.

So in summary (simplified by assuming fr takes only one parameter; x degenerates to x - 1, x - 2... in recursion):

  • We define the core calculations as fn: def fn fr x = ...accumulate x with result from (fr (- x 1)), this is the almost-useful function - although we cannot use fn directly on x, it will be useful very soon. This non-recursive fn uses a function fr to calculate its result
  • fn fr = fr, fr is the fix-point of fn, fr is the useful funciton, we can use fr on x to get our result
  • Y fn = fr, Y returns the fix-point of a function, Y turns our almost-useful function fn into useful fr

Deriving Y (not included)

I will skip the derivation of Y and go to understanding Y. Mike Vainer's post has a lot of details.

The form of Y

Y is defined as (in lambda calculus format):

Y f = ?s.(f (s s)) ?s.(f (s s))

If we replace the variable s in the left of the functions, we get

Y f = ?s.(f (s s)) ?s.(f (s s))
=> f (?s.(f (s s)) ?s.(f (s s)))
=> f (Y f)

So indeed, the result of (Y f) is the fix-point of f.

Why does (Y f) work?

Depending the signature of f, (Y f) can be a function of any arity, to simplify, let's assume (Y f) only takes one parameter, like our factorial function.

def fn fr x = accumulate x (fr (- x 1))

since fn fr = fr, we continue

=> accumulate x (fn fr (- x 1))
=> accumulate x (accumulate (- x 1) (fr (- x 2)))
=> accumulate x (accumulate (- x 1) (accumulate (- x 2) ... (fn fr 1)))

the recursive calculation terminates when the inner-most (fn fr 1) is the base case and fn doesn't use fr in the calculation.

Looking at Y again:

fr = Y fn = ?s.(fn (s s)) ?s.(fn (s s))
=> fn (?s.(fn (s s)) ?s.(fn (s s)))

So

fr x = Y fn x = fn (?s.(fn (s s)) ?s.(fn (s s))) x

To me, the magical parts of this setup are:

  • fn and fr interdepend on each other: fr 'wraps' fn inside, every time fr is used to calculate x, it 'spawns' ('lifts'?) an fn and delegates the calculation to that fn (passing in itself fr and x); on the other hand, fn depends on fr and uses fr to calculate result of a smaller problem x-1.
  • At the time fr is used to define fn (when fn uses fr in its operations), the real fr is not yet defined.
  • It's fn which defines the real business logic. Based on fn, Y creates fr - a helper function in a specific form - to facilitate the calculation for fn in a recursive manner.

It helped me understanding Y this way at the moment, hope it helps.

BTW, I also found the book An Introduction to Functional Programming Through Lambda Calculus very good, I'm only part through it and the fact that I couldn't get my head around Y in the book led me to this post.

JavaScript variable number of arguments to function

While @roufamatic did show use of the arguments keyword and @Ken showed a great example of an object for usage I feel neither truly addressed what is going on in this instance and may confuse future readers or instill a bad practice as not explicitly stating a function/method is intended to take a variable amount of arguments/parameters.

function varyArg () {
    return arguments[0] + arguments[1];
}

When another developer is looking through your code is it very easy to assume this function does not take parameters. Especially if that developer is not privy to the arguments keyword. Because of this it is a good idea to follow a style guideline and be consistent. I will be using Google's for all examples.

Let's explicitly state the same function has variable parameters:

function varyArg (var_args) {
    return arguments[0] + arguments[1];
}

Object parameter VS var_args

There may be times when an object is needed as it is the only approved and considered best practice method of an data map. Associative arrays are frowned upon and discouraged.

SIDENOTE: The arguments keyword actually returns back an object using numbers as the key. The prototypal inheritance is also the object family. See end of answer for proper array usage in JS

In this case we can explicitly state this also. Note: this naming convention is not provided by Google but is an example of explicit declaration of a param's type. This is important if you are looking to create a more strict typed pattern in your code.

function varyArg (args_obj) {
    return args_obj.name+" "+args_obj.weight;
}
varyArg({name: "Brian", weight: 150});

Which one to choose?

This depends on your function's and program's needs. If for instance you are simply looking to return a value base on an iterative process across all arguments passed then most certainly stick with the arguments keyword. If you need definition to your arguments and mapping of the data then the object method is the way to go. Let's look at two examples and then we're done!

Arguments usage

function sumOfAll (var_args) {
    return arguments.reduce(function(a, b) {
        return a + b;
    }, 0);
}
sumOfAll(1,2,3); // returns 6

Object usage

function myObjArgs(args_obj) {
    // MAKE SURE ARGUMENT IS AN OBJECT OR ELSE RETURN
    if (typeof args_obj !== "object") {
        return "Arguments passed must be in object form!";
    }

    return "Hello "+args_obj.name+" I see you're "+args_obj.age+" years old.";
}
myObjArgs({name: "Brian", age: 31}); // returns 'Hello Brian I see you're 31 years old

Accessing an array instead of an object ("...args" The rest parameter)

As mentioned up top of the answer the arguments keyword actually returns an object. Because of this any method you want to use for an array will have to be called. An example of this:

Array.prototype.map.call(arguments, function (val, idx, arr) {});

To avoid this use the rest parameter:

function varyArgArr (...var_args) {
    return var_args.sort();
}
varyArgArr(5,1,3); // returns 1, 3, 5

What is "android.R.layout.simple_list_item_1"?

android.R.layout.simple_list_item_1, this is row layout file in your res/layout folder which contains the corresponding design for your row in listview. Now we just bind the array list items to the row layout by using mylistview.setadapter(aa);

javac : command not found

You have installed the Java Runtime Environment(JRE) but it doesn't contain javac.

So on the terminal get access to the root user sudo -i and enter the password. Type yum install java-devel, hence it will install packages of javac in fedora.

Attribute Error: 'list' object has no attribute 'split'

what i did was a quick fix by converting readlines to string but i do not recommencement it but it works and i dont know if there are limitations or not

`def getQuakeData():
    filename = input("Please enter the quake file: ")
    readfile = open(filename, "r")
    readlines = str(readfile.readlines())

    Type = readlines.split(",")
    x = Type[1]
    y = Type[2]
    for points in Type:
        print(x,y)
getQuakeData()`

Force youtube embed to start in 720p

Use this, it works 100% _your_videocode?rel=0&vq=hd1080"

How to use the ConfigurationManager.AppSettings

\if what you have posted is exactly what you are using then your problem is a bit obvious. Now assuming in your web.config you have you connection string defined like this

 <add name="SiteSqlServer" connectionString="Data Source=(local);Initial Catalog=some_db;User ID=sa;Password=uvx8Pytec" providerName="System.Data.SqlClient" />

In your code you should use the value in the name attribute to refer to the connection string you want (you could actually define several connection strings to different databases), so you would have

 con.ConnectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

How to have a transparent ImageButton: Android

It's android:background="@android:color/transparent"

<ImageButton
    android:id="@+id/imageButton"
    android:src="@android:drawable/ic_menu_delete"
    android:background="@android:color/transparent"
/>

How do I create a user account for basic authentication?

If you create a user with the advanced user management (from command line: netplwiz), then modify the group, remove users, and add iis_users. They will be able to authenticate to your web page, but not the computer.

Performance of Java matrix math libraries?

Have you taken a look at the Intel Math Kernel Library? It claims to outperform even ATLAS. MKL can be used in Java through JNI wrappers.

C++ Cout & Cin & System "Ambiguous"

This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.

Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.

In this case I'd ask why you're including both cstdlib and stdlib.h; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib puts them in the namespace std in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!

Anyway, your use of using namespace std (which I would recommend against, in future) means that std::system from cstdlib now conflicts with system from stdlib.h. I can't explain what's going on with std::cout and std::cin.

Try removing #include <stdlib.h> and see what happens.

If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.

What integer hash function are good that accepts an integer hash key?

Fast and good hash functions can be composed from fast permutations with lesser qualities, like

  • multiplication with an uneven integer
  • binary rotations
  • xorshift

To yield a hashing function with superior qualities, like demonstrated with PCG for random number generation.

This is in fact also the recipe rrxmrrxmsx_0 and murmur hash are using, knowingly or unknowingly.

I personally found

uint64_t xorshift(const uint64_t& n,int i){
  return n^(n>>i);
}
uint64_t hash(const uint64_t& n){
  uint64_t p = 0x5555555555555555ull; // pattern of alternating 0 and 1
  uint64_t c = 17316035218449499591ull;// random uneven integer constant; 
  return c*xorshift(p*xorshift(n,32),32);
}

to be good enough.

A good hash function should

  1. be bijective to not loose information, if possible and have the least collisions
  2. cascade as much and as evenly as possible, i.e. each input bit should flip every output bit with probability 0.5.

Let's first look at the identity function. It satisfies 1. but not 2. :

identity function

Input bit n determines output bit n with a correlation of 100% (red) and no others, they are therefore blue, giving a perfect red line across.

A xorshift(n,32) is not much better, yielding one and half a line. Still satisfying 1., because it is invertible with a second application.

xorshift

A multiplication with an unsigned integer ("Knuth's multiplicative method") is much better, cascading more strongly and flipping more output bits with a probability of 0.5, which is what you want, in green. It satisfies 1. as for each uneven integer there is a multiplicative inverse.

knuth

Combining the two gives the following output, still satisfying 1. as the composition of two bijective functions yields another bijective function.

knuth•xorshift

A second application of multiplication and xorshift will yield the following:

proposed hash

Or you can use Galois field multiplications like GHash, they have become reasonably fast on modern CPUs and have superior qualities in one step.

   uint64_t const inline gfmul(const uint64_t& i,const uint64_t& j){           
     __m128i I{};I[0]^=i;                                                          
     __m128i J{};J[0]^=j;                                                          
     __m128i M{};M[0]^=0xb000000000000000ull;                                      
     __m128i X = _mm_clmulepi64_si128(I,J,0);                                      
     __m128i A = _mm_clmulepi64_si128(X,M,0);                                      
     __m128i B = _mm_clmulepi64_si128(A,M,0);                                      
     return A[0]^A[1]^B[1]^X[0]^X[1];                                              
   }

What is a practical use for a closure in JavaScript?

I'm trying to learn closures and I think the example that I have created is a practical use case. You can run a snippet and see the result in the console.

We have two separate users who have separate data. Each of them can see the actual state and update it.

_x000D_
_x000D_
function createUserWarningData(user) {
  const data = {
    name: user,
    numberOfWarnings: 0,
  };

  function addWarning() {
    data.numberOfWarnings = data.numberOfWarnings + 1;
  }

  function getUserData() {
    console.log(data);
    return data;
  }

  return {
    getUserData: getUserData,
    addWarning: addWarning,
  };
}

const user1 = createUserWarningData("Thomas");
const user2 = createUserWarningData("Alex");

//USER 1
user1.getUserData(); // Returning data user object
user1.addWarning(); // Add one warning to specific user
user1.getUserData(); // Returning data user object

//USER2
user2.getUserData(); // Returning data user object
user2.addWarning(); // Add one warning to specific user
user2.addWarning(); // Add one warning to specific user
user2.getUserData(); // Returning data user object
_x000D_
_x000D_
_x000D_

How to create a link to a directory

you should use :

ln -s /home/jake/doc/test/2000/something xxx

Selecting text in an element (akin to highlighting with your mouse)

You can use the following function to select content of any element:

jQuery.fn.selectText = function(){
    this.find('input').each(function() {
        if($(this).prev().length == 0 || !$(this).prev().hasClass('p_copy')) { 
            $('<p class="p_copy" style="position: absolute; z-index: -1;"></p>').insertBefore($(this));
        }
        $(this).prev().html($(this).val());
    });
    var doc = document;
    var element = this[0];
    console.log(this, element);
    if (doc.body.createTextRange) {
        var range = document.body.createTextRange();
        range.moveToElementText(element);
        range.select();
    } else if (window.getSelection) {
        var selection = window.getSelection();        
        var range = document.createRange();
        range.selectNodeContents(element);
        selection.removeAllRanges();
        selection.addRange(range);
    }
};

This function can be called as follows:

$('#selectme').selectText();

Uncompress tar.gz file

Try this:

tar -zxvf file.tar.gz

How do I wrap text in a span?

Try putting your text in another div inside your span:

i.e.

<span><div>some text</div></span>

How to send file contents as body entity using cURL

I know the question has been answered, but in my case I was trying to send the content of a text file to the Slack Webhook api and for some reason the above answer did not work. Anywho, this is what finally did the trick for me:

curl -X POST -H --silent --data-urlencode "payload={\"text\": \"$(cat file.txt | sed "s/\"/'/g")\"}" https://hooks.slack.com/services/XXX

convert base64 to image in javascript/jquery

This is not exactly the OP's scenario but an answer to those of some of the commenters. It is a solution based on Cordova and Angular 1, which should be adaptable to other frameworks like jQuery. It gives you a Blob from Base64 data which you can store somewhere and reference it from client side javascript / html.

It also answers the original question on how to get an image (file) from the Base 64 data:

The important part is the Base 64 - Binary conversion:

function base64toBlob(base64Data, contentType) {
    contentType = contentType || '';
    var sliceSize = 1024;
    var byteCharacters = atob(base64Data);
    var bytesLength = byteCharacters.length;
    var slicesCount = Math.ceil(bytesLength / sliceSize);
    var byteArrays = new Array(slicesCount);

    for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
        var begin = sliceIndex * sliceSize;
        var end = Math.min(begin + sliceSize, bytesLength);

        var bytes = new Array(end - begin);
        for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
            bytes[i] = byteCharacters[offset].charCodeAt(0);
        }
        byteArrays[sliceIndex] = new Uint8Array(bytes);
    }
    return new Blob(byteArrays, { type: contentType });
}

Slicing is required to avoid out of memory errors.

Works with jpg and pdf files (at least that's what I tested). Should work with other mimetypes/contenttypes too. Check the browsers and their versions you aim for, they need to support Uint8Array, Blob and atob.

Here's the code to write the file to the device's local storage with Cordova / Android:

...
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dirEntry) {

                    // Setup filename and assume a jpg file
                    var filename = attachment.id + "-" + (attachment.fileName ? attachment.fileName : 'image') + "." + (attachment.fileType ? attachment.fileType : "jpg");
                    dirEntry.getFile(filename, { create: true, exclusive: false }, function(fileEntry) {
                        // attachment.document holds the base 64 data at this moment
                        var binary = base64toBlob(attachment.document, attachment.mimetype);
                        writeFile(fileEntry, binary).then(function() {
                            // Store file url for later reference, base 64 data is no longer required
                            attachment.document = fileEntry.nativeURL;

                        }, function(error) {
                            WL.Logger.error("Error writing local file: " + error);
                            reject(error.code);
                        });

                    }, function(errorCreateFile) {
                        WL.Logger.error("Error creating local file: " + JSON.stringify(errorCreateFile));
                        reject(errorCreateFile.code);
                    });

                }, function(errorCreateFS) {
                    WL.Logger.error("Error getting filesystem: " + errorCreateFS);
                    reject(errorCreateFS.code);
                });
...

Writing the file itself:

function writeFile(fileEntry, dataObj) {
    return $q(function(resolve, reject) {
        // Create a FileWriter object for our FileEntry (log.txt).
        fileEntry.createWriter(function(fileWriter) {

            fileWriter.onwriteend = function() {
                WL.Logger.debug(LOG_PREFIX + "Successful file write...");
                resolve();
            };

            fileWriter.onerror = function(e) {
                WL.Logger.error(LOG_PREFIX + "Failed file write: " + e.toString());
                reject(e);
            };

            // If data object is not passed in,
            // create a new Blob instead.
            if (!dataObj) {
                dataObj = new Blob(['missing data'], { type: 'text/plain' });
            }

            fileWriter.write(dataObj);
        });
    })
}

I am using the latest Cordova (6.5.0) and Plugins versions:

I hope this sets everyone here in the right direction.

How to automatically start a service when running a docker container?

There's another way to do it that I've always found to be more readable.

Say that you want to start rabbitmq and mongodb when you run it then your CMD would look something like this:

CMD /etc/init.d/rabbitmq-server start && \
    /etc/init.d/mongod start

Since you can have only one CMD per Dockerfile the trick is to concatenate all instructions with && and then use \ for each command to start a new line.

If you end up adding to many of those I suggest you put all your commands in a script file and start it like @larry-cai suggested:

CMD /start.sh

jquery json to string?

Most browsers have a native JSON object these days, which includes parse and stringify methods. So just try JSON.stringify({}) and see if you get "{}". You can even pass in parameters to filter out keys or to do pretty-printing, e.g. JSON.stringify({a:1,b:2}, null, 2) puts a newline and 2 spaces in front of each key.

JSON.stringify({a:1,b:2}, null, 2)

gives

"{\n  \"a\": 1,\n  \"b\": 2\n}"

which prints as

{
  "a": 1,
  "b": 2
}

As for the messing around part of your question, use the second parameter. From http://www.javascriptkit.com/jsref/json.shtml :

The replacer parameter can either be a function or an array of String/Numbers. It steps through each member within the JSON object to let you decide what value each member should be changed to. As a function it can return:

  • A number, string, or Boolean, which replaces the property's original value with the returned one.
  • An object, which is serialized then returned. Object methods or functions are not allowed, and are removed instead.
  • Null, which causes the property to be removed.

As an array, the values defined inside it corresponds to the names of the properties inside the JSON object that should be retained when converted into a JSON object.

Difference between single and double quotes in Bash

Others explained very well and just want to give with simple examples.

Single quotes can be used around text to prevent the shell from interpreting any special characters. Dollar signs, spaces, ampersands, asterisks and other special characters are all ignored when enclosed within single quotes.

$ echo 'All sorts of things are ignored in single quotes, like $ & * ; |.' 

It will give this:

All sorts of things are ignored in single quotes, like $ & * ; |.

The only thing that cannot be put within single quotes is a single quote.

Double quotes act similarly to single quotes, except double quotes still allow the shell to interpret dollar signs, back quotes and backslashes. It is already known that backslashes prevent a single special character from being interpreted. This can be useful within double quotes if a dollar sign needs to be used as text instead of for a variable. It also allows double quotes to be escaped so they are not interpreted as the end of a quoted string.

$ echo "Here's how we can use single ' and double \" quotes within double quotes"

It will give this:

Here's how we can use single ' and double " quotes within double quotes

It may also be noticed that the apostrophe, which would otherwise be interpreted as the beginning of a quoted string, is ignored within double quotes. Variables, however, are interpreted and substituted with their values within double quotes.

$ echo "The current Oracle SID is $ORACLE_SID"

It will give this:

The current Oracle SID is test

Back quotes are wholly unlike single or double quotes. Instead of being used to prevent the interpretation of special characters, back quotes actually force the execution of the commands they enclose. After the enclosed commands are executed, their output is substituted in place of the back quotes in the original line. This will be clearer with an example.

$ today=`date '+%A, %B %d, %Y'`
$ echo $today 

It will give this:

Monday, September 28, 2015 

Git push: "fatal 'origin' does not appear to be a git repository - fatal Could not read from remote repository."

I had the same issue. When I checked my config file I noticed that 'fetch = +refs/heads/:refs/remotes/origin/' was on the same line as 'url = Z:/GIT/REPOS/SEL.git' as shown:

[core]
    repositoryformatversion = 0
    filemode = false
    bare = false
    logallrefupdates = true
    symlinks = false
    ignorecase = true
[remote "origin"]
    url = Z:/GIT/REPOS/SEL.git     fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
[gui]
    wmstate = normal
    geometry = 1109x563+32+32 216 255

At first I did not think that this would have mattered but after seeing the post by Magere I moved the line and that fixed the problem:

[core]
    repositoryformatversion = 0
    filemode = false
    bare = false
    logallrefupdates = true
    symlinks = false
    ignorecase = true
[remote "origin"]
    url = Z:/GIT/REPOS/SEL.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
[gui]
    wmstate = normal
    geometry = 1109x563+32+32 216 255

Enable binary mode while restoring a Database from an SQL dump

If you don't have enough space or don't want to waste time in decompressing it, Try this command.

gunzip < compressed-sqlfile.gz | mysql -u root -p

Don't forget to replace compressed-sqlfile.gz with your compressed file name.

.gz restore will not work without command I provided above.

How to remove a build from itunes connect?

Wait! You can expire a build actually! :)

After 2017 Solution:

Still same at 2021

  1. From the homepage, click My Apps, select your app.

  2. Click the TestFlight tab.

  3. In the sidebar, below Builds, click the platform (iOS or tvOS).

  4. In the table on the right, in the Build column, click the app icon or build string for the build that is missing compliance information.

5.Click Expire Build.

how to Expire Build App store iTunes Connect

Ta-da! Build expired at the App Store Connect.

Means:

Required roles

See Role permissions.

For more information please visit.

Passing multiple values for same variable in stored procedure

You will need to do a couple of things to get this going, since your parameter is getting multiple values you need to create a Table Type and make your store procedure accept a parameter of that type.

Split Function Works Great when you are getting One String containing multiple values but when you are passing Multiple values you need to do something like this....

TABLE TYPE

CREATE TYPE dbo.TYPENAME AS TABLE   (     arg int    )  GO 

Stored Procedure to Accept That Type Param

 CREATE PROCEDURE mainValues   @TableParam TYPENAME READONLY  AS     BEGIN     SET NOCOUNT ON;   --Temp table to store split values   declare @tmp_values table (   value nvarchar(255) not null);        --function splitting values     INSERT INTO @tmp_values (value)    SELECT arg FROM @TableParam      SELECT * FROM @tmp_values  --<-- For testing purpose END 

EXECUTE PROC

Declare a variable of that type and populate it with your values.

 DECLARE @Table TYPENAME     --<-- Variable of this TYPE   INSERT INTO @Table                --<-- Populating the variable   VALUES (331),(222),(876),(932)  EXECUTE mainValues @Table   --<-- Stored Procedure Executed  

Result

╔═══════╗ ║ value ║ ╠═══════╣ ║   331 ║ ║   222 ║ ║   876 ║ ║   932 ║ ╚═══════╝ 

ViewDidAppear is not called when opening app from background

I think registering for the UIApplicationWillEnterForegroundNotification is risky as you may end up with more than one controller reacting to that notification. Nothing garanties that these controllers are still visible when the notification is received.

Here is what I do: I force call viewDidAppear on the active controller directly from the App's delegate didBecomeActive method:

Add the code below to - (void)applicationDidBecomeActive:(UIApplication *)application

UIViewController *activeController = window.rootViewController;
if ([activeController isKindOfClass:[UINavigationController class]]) {
    activeController = [(UINavigationController*)window.rootViewController topViewController];
}
[activeController viewDidAppear:NO];

What is the difference between a framework and a library?

I think you pinned down quite well the difference: the framework provides a frame in which we do our work... Somehow, it is more "constraining" than a simple library.
The framework is also supposed to add consistency to a set of libraries.

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel

We are using a web service along side a web site and when we publish the web site it returns same this error. We found out that by going into IIS and removing the ServiceModel from Modules and the svc-Integrated from the Handler Mappings the error went away.

Choosing the best concurrency list in Java

Any Java collection can be made to be Thread-safe like so:

List newList = Collections.synchronizedList(oldList);

Or to create a brand new thread-safe list:

List newList = Collections.synchronizedList(new ArrayList());

http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#synchronizedList(java.util.List)

CSS get height of screen resolution

In order to get screen resolution you can also use . This link help you very much to resolve.

npm - how to show the latest version of a package

You can see all the version of a module with npm view. eg: To list all versions of bootstrap including beta.

npm view bootstrap versions

But if the version list is very big it will truncate. An --json option will print all version including beta versions as well.

npm view bootstrap versions --json

If you want to list only the stable versions not the beta then use singular version

npm view bootstrap@* versions

Or

npm view bootstrap@* versions --json

And, if you want to see only latest version then here you go.

npm view bootstrap version

How to modify WooCommerce cart, checkout pages (main theme portion)

WooCommerce has a number of options for modifying the cart, and checkout pages. Here are the three I'd recomend:

Use WooCommerce Conditional Tags

is_cart() and is_checkout() functions return true on their page. Example:

if ( is_cart() || is_checkout() ) {
    echo "This is the cart, or checkout page!";
}

Modify the template file

The main, cart template file is located at wp-content/themes/{current-theme}/woocommerce/cart/cart.php

The main, checkout template file is located at wp-content/themes/{current-theme}/woocommerce/checkout/form-checkout.php

To edit these, first copy them to your child theme.

Use wp-content/themes/{current-theme}/page-{slug}.php

page-{slug}.php is the second template that will be used, coming after manually assigned ones through the WP dashboard.

This is safer than my other solutions, because if you remove WooCommerce, but forget to remove this file, the code inside (that may rely on WooCommerce functions) won't break, because it's never called (unless of cause you have a page with slug {slug}).

For example:

  • wp-content/themes/{current-theme}/page-cart.php
  • wp-content/themes/{current-theme}/page-checkout.php

How to "fadeOut" & "remove" a div in jQuery?

if you are anything like me coming from a google search and looking to remove an html element with cool animation, then this could help you:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
    _x000D_
    var $deleteButton = $('.deleteItem');_x000D_
_x000D_
    $deleteButton.on('click', function(event) {_x000D_
    _x000D_
        event.preventDefault();_x000D_
_x000D_
        var $button = $(this);_x000D_
_x000D_
        if(confirm('Are you sure about this ?')) {_x000D_
_x000D_
            var $item = $button.closest('tr.item');_x000D_
_x000D_
            $item.addClass('removed-item')_x000D_
_x000D_
                .one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e) {_x000D_
_x000D_
                    $(this).remove();_x000D_
            });_x000D_
        }_x000D_
      _x000D_
    });_x000D_
    _x000D_
});
_x000D_
/**_x000D_
 * Credit to Sara Soueidan_x000D_
 * @link https://github.com/SaraSoueidan/creative-list-effects/blob/master/css/styles-3.css_x000D_
 */_x000D_
_x000D_
.removed-item {_x000D_
    -webkit-animation: removed-item-animation .8s cubic-bezier(.65,-0.02,.72,.29);_x000D_
    -o-animation: removed-item-animation .8s cubic-bezier(.65,-0.02,.72,.29);_x000D_
    animation: removed-item-animation .8s cubic-bezier(.65,-0.02,.72,.29)_x000D_
}_x000D_
_x000D_
@keyframes removed-item-animation {_x000D_
    0% {_x000D_
        opacity: 1;_x000D_
        -webkit-transform: translateX(0);_x000D_
        -ms-transform: translateX(0);_x000D_
        -o-transform: translateX(0);_x000D_
        transform: translateX(0)_x000D_
    }_x000D_
_x000D_
    30% {_x000D_
        opacity: 1;_x000D_
        -webkit-transform: translateX(50px);_x000D_
        -ms-transform: translateX(50px);_x000D_
        -o-transform: translateX(50px);_x000D_
        transform: translateX(50px)_x000D_
    }_x000D_
_x000D_
    80% {_x000D_
        opacity: 1;_x000D_
        -webkit-transform: translateX(-800px);_x000D_
        -ms-transform: translateX(-800px);_x000D_
        -o-transform: translateX(-800px);_x000D_
        transform: translateX(-800px)_x000D_
    }_x000D_
_x000D_
    100% {_x000D_
        opacity: 0;_x000D_
        -webkit-transform: translateX(-800px);_x000D_
        -ms-transform: translateX(-800px);_x000D_
        -o-transform: translateX(-800px);_x000D_
        transform: translateX(-800px)_x000D_
    }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes removed-item-animation {_x000D_
    0% {_x000D_
        opacity: 1;_x000D_
        -webkit-transform: translateX(0);_x000D_
        transform: translateX(0)_x000D_
    }_x000D_
_x000D_
    30% {_x000D_
        opacity: 1;_x000D_
        -webkit-transform: translateX(50px);_x000D_
        transform: translateX(50px)_x000D_
    }_x000D_
_x000D_
    80% {_x000D_
        opacity: 1;_x000D_
        -webkit-transform: translateX(-800px);_x000D_
        transform: translateX(-800px)_x000D_
    }_x000D_
_x000D_
    100% {_x000D_
        opacity: 0;_x000D_
        -webkit-transform: translateX(-800px);_x000D_
        transform: translateX(-800px)_x000D_
    }_x000D_
}_x000D_
_x000D_
@-o-keyframes removed-item-animation {_x000D_
    0% {_x000D_
        opacity: 1;_x000D_
        -o-transform: translateX(0);_x000D_
        transform: translateX(0)_x000D_
    }_x000D_
_x000D_
    30% {_x000D_
        opacity: 1;_x000D_
        -o-transform: translateX(50px);_x000D_
        transform: translateX(50px)_x000D_
    }_x000D_
_x000D_
    80% {_x000D_
        opacity: 1;_x000D_
        -o-transform: translateX(-800px);_x000D_
        transform: translateX(-800px)_x000D_
    }_x000D_
_x000D_
    100% {_x000D_
        opacity: 0;_x000D_
        -o-transform: translateX(-800px);_x000D_
        transform: translateX(-800px)_x000D_
    }_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width">_x000D_
  <title>JS Bin</title>_x000D_
</head>_x000D_
<body>_x000D_
  _x000D_
  <table class="table table-striped table-bordered table-hover">_x000D_
    <thead>_x000D_
      <tr>_x000D_
        <th>id</th>_x000D_
        <th>firstname</th>_x000D_
        <th>lastname</th>_x000D_
        <th>@twitter</th>_x000D_
        <th>action</th>_x000D_
      </tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
      _x000D_
      <tr class="item">_x000D_
        <td>1</td>_x000D_
        <td>Nour-Eddine</td>_x000D_
        <td>ECH-CHEBABY</td>_x000D_
        <th>@__chebaby</th>_x000D_
        <td><button class="btn btn-danger deleteItem">Delete</button></td>_x000D_
      </tr>_x000D_
      _x000D_
      <tr class="item">_x000D_
        <td>2</td>_x000D_
        <td>John</td>_x000D_
        <td>Doe</td>_x000D_
        <th>@johndoe</th>_x000D_
        <td><button class="btn btn-danger deleteItem">Delete</button></td>_x000D_
      </tr>_x000D_
      _x000D_
      <tr class="item">_x000D_
        <td>3</td>_x000D_
        <td>Jane</td>_x000D_
        <td>Doe</td>_x000D_
        <th>@janedoe</th>_x000D_
        <td><button class="btn btn-danger deleteItem">Delete</button></td>_x000D_
      </tr>_x000D_
    </tbody>_x000D_
  </table>_x000D_
  _x000D_
<script src="https://code.jquery.com/jquery.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

What is the difference between UTF-8 and ISO-8859-1?

My reason for researching this question was from the perspective, is in what way are they compatible. Latin1 charset (iso-8859) is 100% compatible to be stored in a utf8 datastore. All ascii & extended-ascii chars will be stored as single-byte.

Going the other way, from utf8 to Latin1 charset may or may not work. If there are any 2-byte chars (chars beyond extended-ascii 255) they will not store in a Latin1 datastore.

How get permission for camera in android.(Specifically Marshmallow)

check using this
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA)
            == PackageManager.PERMISSION_DENIED)

and

Php artisan make:auth command is not defined

For Laravel >=6

composer require laravel/ui
php artisan ui vue --auth
php artisan migrate

Reference : Laravel Documentation for authentication

it looks you are not using Laravel 5.2, these are the available make commands in L5.2 and you are missing more than just the make:auth command

    make:auth           Scaffold basic login and registration views and routes
    make:console        Create a new Artisan command
    make:controller     Create a new controller class
    make:entity         Create a new entity.
    make:event          Create a new event class
    make:job            Create a new job class
    make:listener       Create a new event listener class
    make:middleware     Create a new middleware class
    make:migration      Create a new migration file
    make:model          Create a new Eloquent model class
    make:policy         Create a new policy class
    make:presenter      Create a new presenter.
    make:provider       Create a new service provider class
    make:repository     Create a new repository.
    make:request        Create a new form request class
    make:seeder         Create a new seeder class
    make:test           Create a new test class
    make:transformer    Create a new transformer.

Be sure you have this dependency in your composer.json file

    "laravel/framework": "5.2.*",

Then run

    composer update

Splitting dataframe into multiple dataframes

You can use the groupby command, if you already have some labels for your data.

 out_list = [group[1] for group in in_series.groupby(label_series.values)]

Here's a detailed example:

Let's say we want to partition a pd series using some labels into a list of chunks For example, in_series is:

2019-07-01 08:00:00   -0.10
2019-07-01 08:02:00    1.16
2019-07-01 08:04:00    0.69
2019-07-01 08:06:00   -0.81
2019-07-01 08:08:00   -0.64
Length: 5, dtype: float64

And its corresponding label_series is:

2019-07-01 08:00:00   1
2019-07-01 08:02:00   1
2019-07-01 08:04:00   2
2019-07-01 08:06:00   2
2019-07-01 08:08:00   2
Length: 5, dtype: float64

Run

out_list = [group[1] for group in in_series.groupby(label_series.values)]

which returns out_list a list of two pd.Series:

[2019-07-01 08:00:00   -0.10
2019-07-01 08:02:00   1.16
Length: 2, dtype: float64,
2019-07-01 08:04:00    0.69
2019-07-01 08:06:00   -0.81
2019-07-01 08:08:00   -0.64
Length: 3, dtype: float64]

Note that you can use some parameters from in_series itself to group the series, e.g., in_series.index.day

Hide Text with CSS, Best Practice?

I realize this is an old question, but the Bootstrap framework has a built in class (sr-only) to handle hiding text on everything but screen readers:

<a href="/" class="navbar-brand"><span class="sr-only">Home</span></a>

How to use LDFLAGS in makefile

Your linker (ld) obviously doesn't like the order in which make arranges the GCC arguments so you'll have to change your Makefile a bit:

CC=gcc
CFLAGS=-Wall
LDFLAGS=-lm

.PHONY: all
all: client

.PHONY: clean
clean:
    $(RM) *~ *.o client

OBJECTS=client.o
client: $(OBJECTS)
    $(CC) $(CFLAGS) $(OBJECTS) -o client $(LDFLAGS)

In the line defining the client target change the order of $(LDFLAGS) as needed.

Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)

By converting the matrix to array by using

n12 = np.squeeze(np.asarray(n2))

X12 = np.squeeze(np.asarray(x1))

solved the issue.

Android marshmallow request permission?

Starting in Android Marshmallow, we need to request the user for specific permissions. We can also check through code if the permission is already given. Here is a list of commonly needed permissions:

  • android.permission_group.CALENDAR

    • android.permission.READ_CALENDAR
    • android.permission.WRITE_CALENDAR
  • android.permission_group.CAMERA

    • android.permission.CAMERA
  • android.permission_group.CONTACTS

    • android.permission.READ_CONTACTS
    • android.permission.WRITE_CONTACTS
    • android.permission.GET_ACCOUNTS
  • android.permission_group.LOCATION

    • android.permission.ACCESS_FINE_LOCATION
    • android.permission.ACCESS_COARSE_LOCATION
  • android.permission_group.MICROPHONE

    • android.permission.RECORD_AUDIO
  • android.permission_group.PHONE

    • android.permission.READ_PHONE_STATE
    • android.permission.CALL_PHONE
    • android.permission.READ_CALL_LOG
    • android.permission.WRITE_CALL_LOG
    • android.permission.ADD_VOICEMAIL
    • android.permission.USE_SIP
    • android.permission.PROCESS_OUTGOING_CALLS
  • android.permission_group.SENSORS

    • android.permission.BODY_SENSORS
  • android.permission_group.SMS

    • android.permission.SEND_SMS
    • android.permission.RECEIVE_SMS
    • android.permission.READ_SMS
    • android.permission.RECEIVE_WAP_PUSH
    • android.permission.RECEIVE_MMS
    • android.permission.READ_CELL_BROADCASTS
  • android.permission_group.STORAGE

    • android.permission.READ_EXTERNAL_STORAGE
    • android.permission.WRITE_EXTERNAL_STORAGE

Here is sample code to check for permissions:

if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
    if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.WRITE_CALENDAR)) {
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
        alertBuilder.setCancelable(true);
        alertBuilder.setMessage("Write calendar permission is necessary to write event!!!");
        alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            public void onClick(DialogInterface dialog, int which) {
                ActivityCompat.requestPermissions((Activity)context, new String[]{Manifest.permission.WRITE_CALENDAR}, MY_PERMISSIONS_REQUEST_WRITE_CALENDAR);
            }
        });
    } else {
        ActivityCompat.requestPermissions((Activity)context, new String[]{Manifest.permission.WRITE_CALENDAR}, MY_PERMISSIONS_REQUEST_WRITE_CALENDAR);
    }
}

R: how to label the x-axis of a boxplot

If you read the help file for ?boxplot, you'll see there is a names= parameter.

     boxplot(apple, banana, watermelon, names=c("apple","banana","watermelon"))

enter image description here

BigDecimal equals() versus compareTo()

The answer is in the JavaDoc of the equals() method:

Unlike compareTo, this method considers two BigDecimal objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).

In other words: equals() checks if the BigDecimal objects are exactly the same in every aspect. compareTo() "only" compares their numeric value.

As to why equals() behaves this way, this has been answered in this SO question.

Get the current language in device

Answers above don't distinguish between simple chinese and traditinal chinese. Locale.getDefault().toString() works which returns "zh_CN", "zh_TW", "en_US" and etc.

References to : https://developer.android.com/reference/java/util/Locale.html, ISO 639-1 is OLD.

GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag

Just after your Page_Load add this:

public override void VerifyRenderingInServerForm(Control control)
{
    //base.VerifyRenderingInServerForm(control);
}

Note that I don't do anything in the function.

EDIT: Tim answered the same thing. :) You can also find the answer Here

Jenkins restrict view of jobs per user

Only one plugin help me: Role-Based Strategy :

wiki.jenkins-ci.org/display/JENKINS/Role+Strategy+Plugin

But official documentation (wiki.jenkins-ci.org/display/JENKINS/Role+Strategy+Plugin) is deficient.

The following configurations worked for me:

configure-role-strategy-plugin-in-jenkins

Basically you just need to create roles and match them with job names using regex.